AJAX error handling for submit function in functions file

by user13286   Last Updated May 15, 2019 19:08 PM

I have created a custom function in my functions.php to handle form submissions for a Mailchimp subscriber list. I am making an AJAX call in my JavaScript to process the PHP. The problem I am facing is that my AJAX call always returns "success" even when the Mailchimp function is not successful. When the Mailchimp subscribe function is successful it will return code 200, when its unsuccessful it will return code 400. How can I reconfigure my JS so that code 400 will fire the error function in the AJAX call?

Here's part of my PHP function:

curl_setopt($mchAPI, CURLOPT_URL, 'https://' . substr($apiKey, strpos($apiKey, '-') + 1) . '.api.mailchimp.com/3.0/lists/' . $listID . '/members/' . md5(strtolower($email)));
curl_setopt($mchAPI, CURLOPT_HTTPHEADER, array('Content-Type: application/json', 'Authorization: Basic ' . base64_encode('user:' . $apiKey)));
curl_setopt($mchAPI, CURLOPT_USERAGENT, 'PHP-MCAPI/2.0');
curl_setopt($mchAPI, CURLOPT_RETURNTRANSFER, true);
curl_setopt($mchAPI, CURLOPT_CUSTOMREQUEST, 'PUT');
curl_setopt($mchAPI, CURLOPT_TIMEOUT, 10);
curl_setopt($mchAPI, CURLOPT_POST, true);
curl_setopt($mchAPI, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($mchAPI, CURLOPT_POSTFIELDS, json_encode($data));

$result = curl_exec($mchAPI);
$responseCode = curl_getinfo($mchAPI, CURLINFO_HTTP_CODE); // This will return '200' if successful or '400' if unsuccessful

Here's my AJAX call:

$.ajax({
    url: postURL, 
    method: 'POST',
    data: serialized,
    success: function(response) {
        // Always ends here even if subscribe is unsuccesful
        alert('SUCCESS!');
    },
    error: function(xhr, ajaxOptions, thrownerror) {
        alert('FAILED ' + thrownerror);
    }
});


Related Questions


Updated April 12, 2018 19:08 PM

Updated February 21, 2019 18:08 PM

Updated August 15, 2016 08:03 AM

Updated April 24, 2019 08:08 AM

Updated June 12, 2016 08:03 AM