How can I reconfigure my JS so that code
400will fire the error
function in the AJAX call?
The error callback in your $.ajax() setup will be fired if the server responded with a HTTP status header other than “OK” (code: 200), so via the PHP function which handles the AJAX request, just send a HTTP status header with the code 400 (“Bad Request”) when the $responseCode is 400.
And you can send it using wp_die():
add_action( 'wp_ajax_your-action', function(){
...
$responseCode = curl_getinfo($mchAPI, CURLINFO_HTTP_CODE);
// Send a response and the HTTP status header.
if ( '200' == $responseCode ) {
echo 'Subscribed'; // success message/data
wp_die(); // here the code defaults to 200
} else {
echo 'Not subscribed'; // error message/data
wp_die( '', 400 );
}
} );
Or use status_header() to send custom HTTP error message; i.e. other than the default Bad Request when the code is 400:
add_action( 'wp_ajax_your-action', function(){
...
$responseCode = curl_getinfo($mchAPI, CURLINFO_HTTP_CODE);
// Send a response and the HTTP status header.
if ( '200' == $responseCode ) {
echo 'Subscribed'; // success message/data
status_header( 200, 'OK' );
} else {
echo 'Not subscribed'; // error message/data
status_header( 400, 'Custom HTTP Error' );
}
die(); // not wp_die()
} );