Search code examples
javascriptphpxmlhttprequestdom-events

Send errorcode response for Ajax Call


I am trying to write some PHP to send either a successful result or an error code in response to an Ajax request.

I have the following (incomplete) JavaScript:

var xhr=new XMLHttpRequest();
xhr.open('GET', url);
xhr.onload=function() {
    // …
};
xhr.onerror = function() {
    // …
};
xhr.send();

The plan is to get PHP to send either a usable response or to return an error which will be caught by xhr.onerror.

I know how to send a suitable response from PHP, but I have no idea how to send something from PHP which will trigger the error event to JavaScript.

What do I need to return in PHP to get this result?

Note: I know how to generate notional error responses in PHP and to handle them in JavaScript. This is specifically on triggering the error event.


Solution

  • "onerror" fires when there is a failure on the network level also a denied cross-domain request . You can write a logic in such a way that getting a certain response from server means error well thats what i do