1

The AJAX script successfully sends the data to the PHP script and then that inserts the value into the database all without the page refreshing. However, the problem is that on a success the value is not outputted from PHP to the page (error outputting is fine). The form just says 'posting...' and stalls until you refresh it and the value appears from the database.

Below is my JS code:

$(document).ready(function(){
  var form = $('form');
  var submit = $('#submit');
  form.on('submit', function(e) {
      e.preventDefault();
      $.ajax({
          url: 'ajax_comment.php',
          type: 'POST',
          cache: false,
          data: form.serialize(),
          beforeSend: function(){
              submit.val('Posting...').attr('disabled', 'disabled');
          },
          success: function(data){
            var data_code = data.substring(0,3);
            var return_message = data.substring(3); // this is return message without code

            if(data_code == 100) { 
              var item = $(return_message).hide().fadeIn(800);
              $('.new-comment').append(item);

              form.trigger('reset');
              submit.val('Submit Comment').removeAttr('disabled');
            } else if(data_code == 200) {
              //its a fail
              alert("Error: " + return_message);
            }
         }
      });
  });
});

This is the page that the AJAX sends the data to:

    if(empty($order_id) === true || empty($comment) === true) {
    echo "200comment or order id is empty";
    exit();
} else if($num_rows_reviewed> 0) {
    echo "200";
    exit();
} elseif($no_id_match == 0) {
    echo "200";
    exit();
} elseif(strlen($comment) > 499) {
   echo "200 comment cannot be bigger then 499";
    exit();
} else {
   echo"100"; // all is good
   ?>  <div class="comment-item">
         <div class="comment-post">
           <h3><?php echo $name; ?>: <span><?php echo $date; ?></span></h3>
           <p><?php echo $comment; ?></p>
         </div>
       </div>
   <?php }

I am really struggling with this and I am not sure where to go from here! This is so close to working but I do not know how to solve it. The error output messages come through fine it is only the success message and the data that does not come through as required.

Many thanks in advance!


EDIT

Uncaught Error: Syntax error, unrecognized expression: 100this    <div class="comment-item">
  <div class="comment-post">
    <h3>Andrew D: <span>17th March 2014</span></h3>
    <p>hi</p>
  </div>
</div> 

EDIT2

100this    <div class="comment-item">
  <div class="comment-post">
    <h3>Andrew D: <span>17th March 2014</span></h3>
    <p>hi</p>
  </div>
</div>
9
  • Is there an error in the JavaScript of the success handler? Check the JavaScript console. Any error from within that function could cause this behavior. Step through the function in your browser's debugger and see if it does what you expect it to do, examining the runtime values. Commented Mar 17, 2014 at 15:01
  • What does console.log(data) give you, also I'd suggest using json in your response. Commented Mar 17, 2014 at 15:03
  • try adding datatype: "html" to the ajax request... I'm not sure but maybe $(return_message) is throwing a syntax error. Commented Mar 17, 2014 at 15:20
  • Add an error handler to the ajax request. Commented Mar 17, 2014 at 15:31
  • Please see the above edit, I have added the response from the console. I was given Uncaught Error: Syntax error, unrecognized expression:. How can I fix this? Please see the edit for the syntax. Commented Mar 17, 2014 at 15:55

1 Answer 1

1

I think you need a clean response... So, your mistakes:

  1. You didn't gave a dataType for the ajax request, to stop unwanted parsing you should use it.
  2. If you are using ajax, you should use JSON for returning data, and not decoding data with string manipulation
  3. You can't use animations on nonexistent html elements
  4. You have your error in your php file. You can see the logged out text what the browser is receiving from the php script. You should check the php file for errors, somewhere between echo "100" and the div tag. Probably you didn't copied everything from the php file

So you should try the followings!

PHP

$response = new stdClass();
$response->code = 200;
$repsonse->message = "";
if (empty($order_id) === true || empty($comment) === true) {
    $repsonse->message = "comment or order id is empty";
} else if ($num_rows_reviewed > 0) {
} else if ($no_id_match == 0) {
} else if (strlen($comment) > 499) {
    $repsonse->message = "comment cannot be bigger then 499";
} else {
    $response->code = 100;
    $repsonse->message = "<div class=\"comment-item newItem\" style=\"display: none;\">
        <div class=\"comment-post\">
            <h3>".$name.": <span>".$date."</span></h3>
            <p>".$comment."</p>
         </div>
         </div>";
}
echo json_encode($response, JSON_NUMERIC_CHECK);

JAVASCRIPT AJAX request

$.ajax({
      url: 'ajax_comment.php',
      type: 'POST',
      cache: false,
      dataType: 'json',
      data: form.serialize(),
      beforeSend: function(){
          submit.val('Posting...').attr('disabled', 'disabled');
      },
      success: function(data){

        if(data.code === 100 ) { 
          $('.new-comment').append(data.message);
          $('.new-comment div.newItem').fadeIn(800).removeClass('newItem');

          form.trigger('reset');
          submit.val('Submit Comment').removeAttr('disabled');
        } else if(data.code == 200) {
          //its a fail
          alert("Error: " + data.message);
        }
     }
});

Sorry, I've made a mistake, try the new code.

Regards, hotzu

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.