weixin_33747129 2017-09-21 00:33 采纳率: 0%
浏览 24

Ajax联系表问题

I am trying to put together a simple contact form with ajax, where users are not redirected to the contact.php file once the submission is done..

There is no errors.. I am always redirected..

Any idea please? Any suggestion is highly appreciated. Thanks!

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;
});
  • 写回答

3条回答 默认 最新

  • DragonWar% 2017-09-21 00:35
    关注

    You need to prevent the default form behavior.

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

报告相同问题?