doujiku1028
doujiku1028
2016-07-02 12:46

使用AJAX启动PHP而无需重新加载页面

已采纳

I have the following HTML form:

<form class="clearfix" method="POST">
 <input name="name" type="textbox" placeholder="Name:">
 <input name="email" type="textbox" placeholder="Email:">
 <textarea name="message" placeholder="Message:"></textarea>
 <input name="submit" type="submit" id="submit" value="submit">
</form>

Which launches a PHP script (which works) but re-directs the user to the empty page containing the PHP (ie. goes to mywebpage.com/send_mail.php). Using AJAX, how can I launch the PHP script in the background without re-loading the page?

I have the following AJAX request but it doesn't seem to work:

$('#submit').click(function(e) {
 e.preventDefault();
 var data = {
    name: $("#name").val(),
    email: $("#email").val(),
    message: $("#msg").val()
 };

 $.ajax({
    url: '../send_mail.php',
    type: 'POST',
    data: data,
    success: function(msg) {
        alert('Email Sent');
    }
 });
});

Any assistance as to why it's not working? At the moment, all it does (when hitting submit) is go straight to the PHP page and seems to ignore the AJAX

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答

2条回答

  • dongqian1925 dongqian1925 5年前

    It's getting reload because it's a submit button and that is added inside form so it's submitting the form on click without waiting for AJAX to get submitted.

    You can use preventDefault() jQuery method to stop the page redirect. Like this,

    $('#submit').click(function(e) {
     e.preventDefault();
     var data = {
        name: $("#name").val(),
        email: $("#email").val(),
        message: $("#msg").val()
     };
    
     $.ajax({
        url: '../send_mail.php',
        type: 'POST',
        data: data,
        success: function(msg) {
            alert('Email Sent');
        }
     });
    });
    

    When preventDefault(); method is called, the default action of the event will not be triggered.

    You've also missed quotes to specify URL in .ajax().

    jsFiddle: https://jsfiddle.net/3Lpft17y/

    点赞 评论 复制链接分享
  • dongpu42006096 dongpu42006096 5年前

    Use input type as button type = "button" instead of submit.

    点赞 评论 复制链接分享

为你推荐