2

With WP.SE's help I've learned how to send data from a form to WP_REST but now I'm having an issue with returning a custom error. I can successfully pass information to the WP_REST_Response and I've added a check in WP_REST_Response and want it to return the error message back to the AJAX error function but I'm having issues.

For example on my local box the IP is ::1 and if I create a function in PHP:

function ipAddress() {
    if (isset($_SERVER['REMOTE_ADDR'])) :
        $ip_address = clean($_SERVER['REMOTE_ADDR']);
    else :
        $ip_address = "undefined";
    endif;
    return $ip_address;
}

and after researching how to return the check I ran across:

so I added to my WP_REST_Response:

function vader(\WP_REST_Request $request) {
    if (ipAddress() == "::1") :
        return json_encode(array(
            'error' => 'you are localhost'
            ));
    endif;
}

and in my vader.js if I use:

error: function(data) {
    throw data.error;
 },

but I have no errors in the console and it shows {"error":"you are localhost"} but I'm just wanting the value to go to the error function.

Looking at jQuery.ajax() documentation I found statusCode and I can get:

if (ek_ip_address() == "::1") :
    return new WP_Error('foo', 'bar', array('status' => 404));
endif;

and:

statusCode: {
    404: function() {
        $('#testForm').append("thrown 404s");
    }
}

Is there a way to get error to show or am I misunderstanding AJAX error? What am I doing wrong and how can I get the JSON value return from WP_REST_REQUEST to go to the error function?

4
  • in general there is no such thing as "error" in software, "error" is a human concept which is very flexible and depend on context. In this case error is a non 200 http code returned by the server in the response, but if you pay attention even a 404 is never defined as an error in the actual http spec. Aug 17, 2017 at 15:58
  • ... I would just avoid using the term error in my software, and prefer a status field with success/fail over calling a fail an "error". IIRC the wp_json_send (or similar) function let you pass it as parameter to be included in the generated json. Aug 17, 2017 at 16:01
  • Avoiding it doesn't mean I'm learning how to use it if I ever needed to though.
    – user9447
    Aug 17, 2017 at 16:39
  • The point is avoiding thinking in terms of error, and instead thinking about what actually happens, as the term "error" is just confusing. returning 404 from the server in no error in any way, it is just a very poor choice of field name by the jQuery team. In your own code there are no errors as well. A user wantted to login and provided a wrong password? that is not an error as everything works as expected, it is just a "user/password mismatch" Aug 17, 2017 at 16:46

2 Answers 2

3

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.
1
  • Good example. So returning an error message from the API endpoint and stopping further execution on the server is good. The AJAX request is done at that time, so it is up to the server logic to send back a reply in the AJAX response about the error that the server logic produced. Then the user can try again. Good image of explaining this. Thank you.
    – lowtechsun
    Oct 26, 2019 at 10:55
1

As Jack correctly points out, since the request was successful, you will never end up in the error callback. You'd rather need to process whatever your server returned inside the success callback of jQuery.ajax():

success: (data) => {
    if('error' in data) {
        // server returned `error` property in payload - something is wrong!
    }
}

If you're not using ES6:

success:function(data) {
    if(data && typeof data.error !== 'undefined') {
        // show error message to user
    }
}
1
  • There is an issue when using if error: Uncaught TypeError: Cannot use 'in' operator to search for 'error' in error found
    – user9447
    Aug 17, 2017 at 14:54

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.