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

AJAX request saves to database but alerts failed

本文关键字:失败 数据库 请求 保存 AJAX      更新时间:2023-09-26

我有一个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;
        }
    });
});
});

处理并保存到DB的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。没有错误输出到控制台,只是警告说失败。

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

 dataType: 'json',

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

 echo "Nothing posted";

两种解决方案,删除javascript dataType: 'json'中的代码或者在php

中返回json
 $data['result'] = "nothing posted";
 echo json_encode($data);

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

希望有帮助