0

I'm trying to return a useful error message to my AJAX requests that I can use client side to display to the user.

I'm making my requests using jQuery like the following:

$.ajax({
    url: 'myURL.php',
    data: { id: someId },
    type: 'POST',
    success: function(response) {
        // do something with response
    },
    error: function(jqXHR) {
        // here is where I want to do something with jqXHR.responseText
        // but how do I set that in PHP?
    }
});

And if some error occurs in my PHP script, I use the following header:

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

So my question is, how do I include some useful error message in that header that will get put onto the responseText attribute of the jqXHR which I can then use in my jQuery error callback?

Any help is appreciated.

Jon Rubins
  • 4,323
  • 9
  • 32
  • 51
  • Why are you returning an internal server error? You could just send back a useful error message and process that in your `success` function. – jeroen May 06 '14 at 02:41
  • You could do `header("HTTP/1.1 500 Some helpful message");` –  May 06 '14 at 02:41

1 Answers1

0

I typically build a JSON response instead of xml, but the idea should be the same. Rather than returning a server error of any kind, you can build your response off an array containing something like:

array('success'=>true);

or

array('success'=>false, 'message'=>"Couldn't do it because ..blah..");

Then, when I process the json in success:

if(json['success']) { ... } //yay, it worked!  reload the page or something
else if(json['message']) alert(json['message']);
else alert('Unknown error');

This allows your controller to send meaningful messages to the user. Or you can add another array key like ['error'] that you can inspect using your browser's dev console.

Your method may vary, returning something that can be processed by jqXHR, but the idea is similar enough.

Jerbot
  • 1,168
  • 7
  • 18