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:
- Returning JSON from a PHP Script
- Clean way to throw php exception through jquery/ajax and json
- Returning JSON from PHP to JavaScript?
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?