我有一个引导模式联系表单,该表单使用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没有错误输出到控制台,只是警报说失败。

最佳答案

正如路易斯建议的那样,请尝试将适当的 header 添加到保存到数据库的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);
           }
       });
   });
});

希望能有所帮助

07-24 16:41