dqd2800 2015-08-19 20:19
浏览 97
已采纳

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

I have a bootstrap modal contact form which uses AJAX and PHP to save the information sent by a user to a database:

        <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!? anybody know where I'm going wrong, I have attached my script.js and send.php file below:

Javascript/Ajax file:

$(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

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 No errors are output to the console, just the alert saying failed.

  • 写回答

2条回答 默认 最新

  • duanniesui6391 2015-08-19 20:53
    关注

    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:

    <?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:

    $(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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!