简体   繁体   English

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

[英]AJAX request saves to database but alerts failed

I have a bootstrap modal contact form which uses AJAX and PHP to save the information sent by a user to a database: 我有一个引导模式联系表单,该表单使用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>

When I submit the form the page alerts that the AJAX request has failed but yet the information still saves to the database!? 当我提交表单时,页面会警告AJAX请求失败,但是信息仍然保存到数据库中! anybody know where I'm going wrong, I have attached my script.js and send.php file below: 任何人都知道我要去哪里错了,我在下面附加了我的script.js和send.php文件:

Javascript/Ajax file: 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 file for processing and saving to 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";

}

?>

PS No errors are output to the console, just the alert saying failed. PS没有错误输出到控制台,只是警报说失败。

according to your javascript, your ajax is expecting to receive a json result, look at this line 根据您的JavaScript,您的Ajax期望收到json结果,请看此行

 dataType: 'json',

but in your php code you are only echoing a string 但是在您的php代码中,您仅在回显字符串

 echo "Nothing posted";

two solutions , delete this code in your javascript dataType: 'json' or return a json in your php 两个解决方案,请在您的javascript dataType中删除此代码:'json'或在您的php中返回一个json

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

As Luis suggests, try to add proper header to the php file which saves to the database and make the output json object like so: 正如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);

I would use the following alias instead of $.ajax, but it's a personal preference: 我将使用以下别名代替$ .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);
           }
       });
   });
});

Hope that helps 希望能有所帮助

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM