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 如何获取APP内弹出的网址链接
  • ¥15 wifi 图标不见了 不知道怎么办 上不了网 变成小地球了
  • ¥50 STM32单片机传感器读取错误
  • ¥50 power BI 从Mysql服务器导入数据,但连接进去后显示表无数据
  • ¥15 (关键词-阻抗匹配,HFSS,RFID标签)
  • ¥50 sft下载大文阻塞卡死
  • ¥15 机器人轨迹规划相关问题
  • ¥15 word样式右侧翻页键消失
  • ¥15 springboot+vue 集成keycloak sso到阿里云
  • ¥15 win7系统进入桌面过一秒后突然黑屏