doujiku1028 2016-07-02 12:46
浏览 31
已采纳

使用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 2016-07-02 12:51
    关注

    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/

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 关于大棚监测的pcb板设计
  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器
  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)
  • ¥15 Vue3地图和异步函数使用
  • ¥15 C++ yoloV5改写遇到的问题
  • ¥20 win11修改中文用户名路径
  • ¥15 win2012磁盘空间不足,c盘正常,d盘无法写入