JamesB
JamesB

Reputation: 197

How to create and handle response for Ajax call

How is the correct way to handle success/error results in my PHP script? I have a function in the script, and it either fails or succeeds. Normally, I would return true or false.

But if I understand correctly, Ajax success function doesn't care about the result in my script, it only cares whether or not it actually ran my script. In other words, I have to, confusingly, check for errors in the success function.

So how should I have PHP return error, and how do I check for it in the success function? Should I have PHP simply "echo "true";" if it succeeds?

    $.ajax({
        type: 'POST',
        url: 'jquery-actions.php',
        data: formData,
        dataType: 'text',
        encode: true,
        error: function (response) {
            console.log(response);
        },
        success: function (response) {
            //How to find out whether or not PHP function worked?
        }

Upvotes: 1

Views: 2490

Answers (2)

guest271314
guest271314

Reputation: 1

Try

$.ajax({
    type: 'POST',
    url: 'jquery-actions.php',
    data: formData,
    dataType: 'text',
    encode: true
}) 
.always(function(jqxhr, textStatus, errorThrown) {
  // `success`
  if (typeof jqxhr === "string" 
       && textStatus !== "error"
       && jqxhr == "true") {
     console.log(jqxhr)
  } 
  // `error`
  else if (jqxhr == "false" 
           || typeof jqxhr === "object"
           || textStatus === "error") {
     console.log(jqxhr, errorThrown)
  }
})

Upvotes: 1

Rory McCrossan
Rory McCrossan

Reputation: 337570

You are correct in that the error handler of the $.ajax call only executes if the response code from the request is anything other than 200 OK. If you code executes correctly, but you have an error which you want the client side to handle, you would could return a flag indicating the state of the response. Assuming you use JSON, it may look something like this:

{
    success: true,
    additionalData: 'foo bar'
}

Then you can check that flag in your success handler:

$.ajax({
    type: 'POST',
    url: 'jquery-actions.php',
    data: formData,
    dataType: 'text',
    encode: true,
    error: function (response) {
        console.log(response);
    },
    success: function (response) {
        if (response.success) {
            console.log('it worked!');
        } else {
            console.log('there was a problem...');
            console.log(response.additionalData);
        }
    }

Alternatively you could force your PHP to return a 500 error:

header("HTTP/1.1 500 Internal Server Error");

However you would not be able to send additional data with this method, meaning error messages would have to be kept in client side code.

Upvotes: 1

Related Questions