WP REST return value to error function from Request

An Ajax call can be sent to anywhere. It can be a server running a PHP, a virtual local route that is simulated using C#, or anything else. So, Ajax does not care what the response is, since it can’t understand it.

When you are sending any data back from your server, as long as the status is 200 ( or anything but an error ), the Ajax script considers this a successful request. Afterward, it’s up to you to handle the situation based on your response.

A Simple Example

I’m a novice at English language. I use the “error” word instead of “success” and return it as a response.

$data['status'] = 'error';
$data['message'] = 'Nice! Request has been done.';
return $data;

The server did successfully run the task, but has sent the wrong status. How would Ajax know that?

So, the error section of an Ajax call is for when there is a problem making the request, before it’s finished, not after. After the response has been sent, Ajax did its job, it’s considered a successful request.

Real Life Example

  1. Let’s say you write a letter for a friend, and ask him do join you in
    a business. You are the “user” here.
  2. You give your letter to the post man for delivery. The post man is
    the “Ajax” function here.
  3. Your friend write a very big “NO” in his response (how rude),
    seals the letter and passes it back to the post man. Your friend is the “server” here.
  4. The post man delivers the letter back to you. The post man did his job, no matter what the response was. So he is considered a “successful” one at his job. (don’t forget his tip)
  5. It’s up to you to choose whether to scream, shout or cry because of
    your friend’s strict “NO” (Error handling). It’s not the post
    man’s problem.