簡體   English   中英

Ajax聯系表問題

[英]Issue with Ajax Contact Form

我正在嘗試將一個簡單的聯系表單與ajax放在一起,一旦提交完成,用戶就不會重定向到contact.php文件。

沒有錯誤..我總是被重定向..

有什么想法嗎? 任何建議都將受到高度贊賞。 謝謝!

contact.html

<!DOCTYPE html>
<html>
<head>
    <title></title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
    <script src="main.js"></script>

</head>
<body>

    <form action="contact.php" method="post" class="ajax">
        <div>
            <input type="text" name="name" placeholder="Your Name">
        </div>
        <div>
            <input type="email" name="email" placeholder="Your Email">
        </div>
        <div>
            <textarea name="message" placeholder="Your Message"></textarea>
        <div>
            <input type="submit" value="Send">
    </form>


</body>
</html>

contact.php

<?php 

if(isset($_POST['name'], $_POST['email'], $_POST['message'], $_POST['name'])) {
    print_r($_POST);
}


?>

main.js

$('form.ajax').on('submit', function() { 
        var that = $(this), 
        url = that.attr('action'), 
        type = that.attr('method'), 
        data = {}; 

    that.find('[name]').each(function(index, value) {
        var that = $(this),
        name = that.attr('name'),
        value = that.val();

        data[name] = value;

    });

    $.ajax({
        url: url,
        type: type,
        data: data,

        success:function(response) {
            console.log(response);
        }

    });

     return false;
});

您需要防止默認的表單行為。

$('form.ajax').on('submit', function(evt) { 
      evt.preventDefault();

您需要輸出json格式,因此需要設置標頭,並且需要將json值返回給ajax成功,因此需要json_encode($ object_or_array_form_php);

 <?php 

if(isset($_POST['name'], $_POST['email'], $_POST['message'], $_POST['name'])) {
   header("Content-type:application/json");
   $_POST['success'] = "You form is sending ...";
   echo json_encode($_POST); //this is the "response" param form ajax
}


?>

砍死! 這有點不同..

<script>
        $(document).ready(function() {

            $('form').submit(function (event) {
                event.preventDefault();
                var name = $("#mail-name").val();
                var email = $("#mail-email").val();
                var message = $("#mail-message").val();
                var submit = $("#mail-submit").val();
                $(".form-message").load("contact.php", {
                    name: name,
                    email: email,
                    message: message,
                    submit: submit
                });
            });

        });
    </script>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM