0

After much struggling and reading online I still cannot find an answer for this question. In my application the form gets sent via AJAX then in PHP it is validated and added to the database. However, I can send a success message but I do not know how to send a friendly error message back to the user.

Below is my JS:

$(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 item = $(data).hide().fadeIn(800);
              $('.new-comment').append(item);

              form.trigger('reset');
              submit.val('Submit Comment').removeAttr('disabled');
          },
          error: function(e){
              alert(e);
          }
      });
  });
});

I have little experience in AJAX so please be simple with me! The error messages will be along the lines of 'Username does not exist' etc so I don't think I could do this with client side validation. Thanks in advance!


EDIT: Below is my PHP code that I am using.

    <?php
// Include files
include 'config.php';

// Variables
$order_id = $_POST['order_id'];  
$comment  = $_POST['comment']; 
$reviewed = 1;
$date     = date('dS F Y');

// Find order ID match 
$stmt = $con->prepare("SELECT order_id FROM transactions WHERE order_id = ?");
$stmt->bind_param('i', $order_id);
$stmt->execute();
$stmt->store_result();
$no_id_match = $stmt->num_rows; 
$stmt->close(); 

// Check if review has already been submitted 
$stmt = $con->prepare("SELECT order_id FROM transactions WHERE order_id = ? AND review = 1");
$stmt->bind_param('i', $order_id);
$stmt->execute();
$stmt->store_result();
$num_rows_reviewed = $stmt->num_rows; 
$stmt->close(); 

if(empty($order_id) === true || empty($comment) === true) {
    exit();
} else if($num_rows_reviewed> 0) {
    exit();
} elseif($no_id_match == 0) {
    exit();
} elseif(strlen($comment) > 499) {
    exit();
} else {
    //Insert review into DB
    $stmt = $con->prepare("INSERT INTO reviews (order_id, comment, date) VALUES (?, ?, ?)");
    $stmt->bind_param('iss', $order_id, $comment, $date);
    $stmt->execute(); 
    $stmt->close();

    // Update transactions to show review added
    $stmt = $con->prepare("UPDATE transactions SET review = ? WHERE order_id = ?");
    $stmt->bind_param('ii', $reviewed, $order_id);
    $stmt->execute(); 
    $stmt->close();

    // Get name from order ID
    $stmt = $con->prepare("SELECT first_name, last_name FROM transactions WHERE order_id = ?");
    $stmt->bind_param('i', $order_id);
    $stmt->execute(); 
    $stmt->bind_result($first_name, $last_name);
    $stmt->fetch();
    $stmt->close();
    $name = $first_name. ' '. mb_substr($last_name, 0, 1);

    // Output review live to page ?>
    <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 
}?>

At the moment the exit() variables are where I would like to validate the script. However since I do not know how to do this right now I am just exiting the script.

4 Answers 4

2

You can send errors from backend with the HTTP way.

Send a PHP array encoded in json if all works fine.

$result = [];
$result['error'] = false;
$result['code'] = "OK"; //better with constant
$result['msg'] = "";
echo json_encode($result);

And like this if something didn't work.

header('HTTP/1.1 500 Internal Server Error');
$result = [];
$result['error'] = false;
$result['code'] = "DB_UPDATE_ERROR"; //better with constant
$result['msg'] = "Impossible save bla, bla, bla";
echo json_encode($result);
Sign up to request clarification or add additional context in comments.

Comments

1

I believe the solution is to add a success/error code (of your own) in very start of your PHP return.

For instance if data (in success clause of ajax) function looks like "Incorrect Login Credentials", (which is coming from PHP of course), you should instead send "200Incorrect Login Information" OR "100Success Login" from PHP.

as you can see with 200 I mean PHP says there was an error / authentication or validation failure and with 100 I mean to tell AJAX that everything was accepted from PHP end.

then you can do this in your jquery:

var data_code = data.substring(0,3);
var return_message = data.substring(3); // this is return message without code

if(data_code == 100) { 
 //its a success
  document.location.replace("success.html");
} else if(data_code == 200) {
 //its a fail
  alert("Error: " + return_message);
}

EDIT:

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

please note that this method works just as expected but its a little tricky, I use it as well where I dont want to use json (as answered by other user).


EDIT

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);
    }
},

6 Comments

Thanks for your help Sidstar! I am still a little confused on what I need to write in my PHP though. Instead of just a normal echo, I need to include a status code right? How does the syntax look for that?
Its actually 200 for all the errors and 100 for success. You just need to make sure its printed at very start of results. Yes you can echo it as well. Add the PHP code so I can explain better.
Hello again! I have just added my PHP code that I am using. Hope this makes things more clear. Thanks
Okay... hmmm sorry can't go thru all that right now but thing if there is a validation fail in your PHP script and you want to show a error message just make sure you echo as "200" first AND if everything else is good, echo a "100" first.
Thanks for updating your answer, massive credit and thank you to you! The last small problem I have is this. Where should I put the jQuery? When I try and put it out of the .$ajax call it just returns a syntax error. Thanks again in advance!
|
0

I would recommend to use JSON as the response format. So you can send an error message in an extra response key. Example

{
   data: "<div>...</div>",
   error: "username does not exist"
}

In your response function you can use the returned keys for accessing the different data.

      success: function(returnedData){
          $('.new-comment').append(returnedData.data);
          if (returnedData.error) $('.error').append(returnedData.error);
      },

Be sure to set the dataType of the ajax request to "json".

Comments

0
$(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(),
      dataType:'json',
      beforeSend: function(){
          submit.val('Posting...').attr('disabled', 'disabled');
      },
      success: function(data){

          if(data.status) {
          var item = $(data).hide().fadeIn(800);
          $('.new-comment').append(item);

          form.trigger('reset');
          submit.val('Submit Comment').removeAttr('disabled');
          } else {
             alert(data.message);
             for(var value in data.fields) {
                alert(data.fields[value]); // can do error placement as well
             }
          }
      },
      error: function(e){
          alert(e);
      }
});
});
});

at ajax_comment.php file Just write code as a example your rest of code if error

$response['status'] = false;
$response['fields']['username'] = 'Not valid';  // fields name should be same like your 
$response['message'] = 'There are some error with given input, please correct'; 

form field name so error placement would be easy

if not any error

$response['status'] = true;
$response['message'] = 'Successfully Submitted'; 

echo json_encode($response);

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.