【问题标题】:AJAX request saves to database but alerts failedAJAX 请求保存到数据库但警报失败
【发布时间】:2015-11-13 07:24:09
【问题描述】:

我有一个引导模式联系表单,它使用 AJAX 和 PHP 将用户发送的信息保存到数据库:

        <div class="modal fade" id="contact" role="dialogue">
    <div class="modal-dialog">
        <div class="modal-content">

            <div class="modal-body">
                <form id="myform" role="form">

                    <div class="form-group">

                        <label for="name">Name: </label>
                        <input type="name" name="name" class="form-control" id="name" >

                    </div>

                    <div class="form-group">

                        <label for="email">Email: </label>
                        <input type="email" name="email" class="form-control" id="email">

                    </div>

                    <div class="form-group">

                        <label for="msg">Message: </label>
                        <textarea class="form-control" name="msg" id="msg" rows="10"></textarea>
                    </div>

                    <!-- <a class="btn btn-primary" data-dismiss="modal">Close</a> -->
                    <button id="sub" type="submit" name="submit" class="btn btn-default">Submit</button>

                </form>
            </div>
        </div>
    </div>
</div>

当我提交表单时,页面提示 AJAX 请求失败但信息仍保存到数据库中!?任何人都知道我哪里出错了,我在下面附上了我的 script.js 和 send.php 文件:

Javascript/Ajax 文件:

$(document).ready(function(){
$('#myform').submit(function(){

    $.ajax({
        type: 'post',
        url: 'send.php',
        dataType: 'json',
        async: true,
        data: $('#myform').serialize(),
        success: function(msg){
            alert("It was a success");
            return false;

        },
        error: function(jqXHR, textStatus, errorThrown){
            alert("Fail");
            console.log(jqXHR + '-' + textStatus + '-' + errorThrown);
            return false;
        }
    });
});
});

用于处理和保存到数据库的 PHP 文件

<?php

include 'connect.php';

if(isset($_POST['name'])&&($_POST['email'])&&($_POST['msg']))
{
$sql = "INSERT INTO details (name, email, message) VALUES (:Name, :Email, :Msg)";

$stmt = $pdo->prepare($sql);

$stmt->bindParam(':Name', $_POST['name'], PDO::PARAM_STR);
$stmt->bindParam(':Email', $_POST['email'], PDO::PARAM_STR);
$stmt->bindParam(':Msg', $_POST['msg'], PDO::PARAM_STR);

$stmt->execute();

echo "done";

}else{

echo "Nothing posted";

}

?>

P.S 没有错误输出到控制台,只是警告说失败。

【问题讨论】:

  • 使用 Fiddler2 等工具或 Chrome F12 网络选项卡检查返回的实际响应。然后你可以看到服务器说什么
  • 您的 ajax 数据类型是 json,尝试在您的 php 文件中编码您的 echo 语句。回声 json_encode('完成');和 echo json_encode('Nothing posted');
  • 感谢所有评论的人。

标签: javascript php jquery ajax twitter-bootstrap


【解决方案1】:

根据您的 javascript,您的 ajax 期望收到 json 结果,请查看此行

 dataType: 'json',

但是在你的 php 代码中你只是在回显一个字符串

 echo "Nothing posted";

两个解决方案,删除javascript dataType中的这段代码:'json' 或者在你的 php 中返回一个 json

 $data['result'] = "nothing posted";
 echo json_encode($data);

【讨论】:

  • 这正是我的做法
  • 感谢 Luis 的输入,我很感激。
【解决方案2】:

按照 Luis 的建议,尝试在保存到数据库的 php 文件中添加适当的标头,并使输出的 json 对象如下所示:

<?php

include 'connect.php';

//The json header
header('Content-type: application/json');
header("Content-Disposition: inline; filename=ajax.json");

if(isset($_POST['name'])&&($_POST['email'])&&($_POST['msg']))
{
    $sql = "INSERT INTO details (name, email, message) VALUES (:Name, :Email, :Msg)";

    $stmt = $pdo->prepare($sql);
    $stmt->bindParam(':Name', $_POST['name'], PDO::PARAM_STR);
    $stmt->bindParam(':Email', $_POST['email'], PDO::PARAM_STR);
    $stmt->bindParam(':Msg', $_POST['msg'], PDO::PARAM_STR);

    $stmt->execute();

    $result = array('success'=>true, 'message'=>'The data has been saved successfuly');

} else {
    $result = array('success'=>false, 'message'=>'Can\'t save the data');
}

//Also is a good practice to omit the php closing tag in order to prevent empty characters which could break the posted headers

echo json_encode($result);

我会使用以下别名而不是 $.ajax,但这是个人喜好:

$(document).ready(function(){
   $('#myform').submit(function(e){
       e.preventDefault(); //Prevent form submission, so the page doesn't refresh
       $.post('send.php', $(this).serialize(), function(response){
           console.log(response); //see what is in the response in the dev console
           if(response.success == true){
               //success action
               //...some code here...
           } else {
               //error action, display the message
               alert(response.message);
           }
       });
   });
});

希望有帮助

【讨论】:

  • 非常感谢 Nik 你的救命稻草,效果很好。如果我通过 php mail 方法将数据发送到哪里而不是将其保存到数据库中,这段代码是否仍然可以正常工作?最好还是像上面那样使用 if 语句来处理 AJAX 请求的成功/失败?我在某处读到了成功:和错误:折旧的地方。感谢您花时间回答我的问题。
  • 你可以在 php 中做任何你想做的事情,重要的部分是打印出来的响应,所以如果你想通过电子邮件发送它 - 这不是问题。关于 if-else 语句 - 这是我的一种编码方式,对我来说比 $.ajax 更直观,即使 $.post 是 $.ajax 的别名 关于成功和错误弃用 - 它们似乎在文档中对我来说。可能它们会被 Promise 取代,但不确定是否会发生
  • 干得好,AJAX 新手,以防你没有注意到哈哈。再次感谢,编码愉快!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-04-02
  • 2018-11-30
  • 2019-01-30
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多