AJAX请求保存到数据库但警报失败

时间:2015-08-19 20:19:12

标签: javascript php jquery ajax twitter-bootstrap

我有一个bootstrap模式联系表单,它使用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没有错误输出到控制台,只是提示失败。

2 个答案:

答案 0 :(得分:4)

根据你的javascript,你的ajax期待收到json结果,看看这一行

 dataType: 'json',

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

 echo "Nothing posted";

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

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

答案 1 :(得分:1)

正如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);
           }
       });
   });
});

希望有所帮助