Ajax 脚本不更改按钮文本


Ajax script not changing button text

我创建了一个注释系统,其中我通过Ajax在我的数据库中插入注释。问题是,它正确地添加了数据库中的注释,但不适用于submit的成功代码。请提出任何建议。

形式

 <h4>Add your Review:</h4>
  <?php
  if(isset($_SESSION["login_email"]) && !empty($_SESSION["login_email"]))
          {
        $email=$_SESSION['login_email'];
          ?>
        <div id="addCommentContainer">
        <form id="addCommentForm" method="post" action="">
         <div>
        <label for="body">Review</label>
         <textarea name="body" id="body" cols="20" rows="5"></textarea>
         <input type="hidden" name="email" id="email" value="<?php echo $email?>" />
        <input type="submit" id="submit" value="Submit" />
        </div>
        </form>
        </div>
             <?php
           }
     else{
       echo "Login to add review!";
        }
        ?>
 </div>

脚本.js

    $(document).ready(function(){
         var working = false;
        $('#addCommentForm').submit(function(e){
            e.preventDefault();
            if(working) return false;
            working = true;
            $('#submit').val('Working..');
            $('span.error').remove();
           $.post('submit.php',$(this).serialize(),function(msg){
          //This code isn't working 
                working = false;
                $('#submit').val('Submit');
                if(msg.status){
            $(msg.html).hide().insertBefore('#addCommentContainer').slideDown();
                    $('#body').val('');
                }
                else {
                $.each(msg.errors,function(k,v){
                $('label[for='+k+']').append('<span class="error">'+v+'</span>');
                    });
                }
            },'json');
        });
    });

提交.php

 <?php
        // Error reporting:
        error_reporting(E_ALL^E_NOTICE);
        include "db/db.php";
        include "comment.class.php";
        /*
        /   This array is going to be populated with either
        /   the data that was sent to the script, or the
        /   error messages.
        /*/
        $arr = array();
        $validates = Comment::validate($arr);
        if($validates)
        {
            /* Everything is OK, insert to database: */
            mysqli_query($con," INSERT INTO comments(email,body,product_id)
                            VALUES (
                                '".$arr['email']."',
                                 '".$arr['body']."',
                                 '".$arr['productid']."'
                            )");

            $arr['dt'] = date('r',time());
            $arr['id'] = mysqli_insert_id($con);
            /*
            /   The data in $arr is escaped for the mysql query,
            /   but we need the unescaped variables, so we apply,
            /   stripslashes to all the elements in the array:
            /*/
            $arr = array_map('stripslashes',$arr);
            $insertedComment = new Comment($arr);

            /* Outputting the markup of the just-inserted comment: */
            echo json_encode(array('status'=>1,'html'=>$insertedComment->markup()));
        }
        else
        {
            /* Outputtng the error messages */
            echo '{"status":0,"errors":'.json_encode($arr).'}';
        }
        ?>

禁用提交按钮,直到您没有收到服务器的响应。

$(document).ready(function() {
    $('#addCommentForm').submit(function(e) {
        e.preventDefault();
        $('#submit').prop("disabled", true);
        $('span.error').remove();
        $.ajax({
            url: "submit.php",
            type: "POST",
            data: $('#addCommentForm').serialize()
            success: function(result) {
                $('#submit').prop("disabled", true);

                if (msg.status) {
                    $(msg.html).hide().insertBefore('#addCommentContainer').slideDown();
                    $('#body').val('');
                } else {
                    $.each(msg.errors, function(k, v) {
                        $('label[for=' + k + ']').append('<span class="error">' + v + '</span>');
                    });
                }
            }
        });
    });
})

.post()后添加.done.fail.always,您将看到错误。在下面的示例代码中,我将打印到控制台。问题似乎是您要求返回的数据采用JSON格式,但您没有以 JSON 格式发送。将数据转换为 JSON,然后发送:

 $.post('submit.php', $(this).serialize(), function (msg) {
     working = false;
     $('#submit').val('Submit');
     if (msg.status) {
         $(msg.html).hide().insertBefore('#addCommentContainer').slideDown();
         $('#body').val('');
     } else {
         $.each(msg.errors, function (k, v) {
              $('label[for=' + k + ']').append('<span class="error">' + v + '</span>');
         });
     }
 }, 'json').done(function () {
     alert("second success");
 }).fail(function (a,b,c) {
     console.log(a);
     console.log(b);
     console.log(c);
 }).always(function () {
     alert("finished");
 });

更新:

确保您的submit.php返回如下 JSON:

echo json_encode($_POST);