PHP Mailchimp API-始终会收到AJAX 200响应,尽管发生错误

时间:2018-06-29 13:14:31

标签: php axios mailchimp mailchimp-api-v3.0

我想使用Mailchimp API和AJAX为用户订阅列表。为此,我使用了PHP Mailchimp API v3 包装器。它工作正常,但是,无论Mailchimp返回400的事实如何,Javascript始终会收到200响应。例如,如果已经订阅了电子邮件地址,我将得到以下信息:

enter image description here enter image description here

如何确保在订阅AJAX请求时出现错误?任何帮助将不胜感激。

PHP

use \DrewM\MailChimp\MailChimp;

$mc_api_key = c::get('mc_api_key');
$list_id = c::get('mc_list');

$MailChimp = new MailChimp($mc_api_key);

$POST = filter_var_array($_POST, FILTER_SANITIZE_STRING);
$email = $POST['email_address'];

$result = $MailChimp->post("lists/$list_id/members/", [
    'email_address' => $email,
    'status'        => 'subscribed',
]);

if ($MailChimp->success()) {
    $mc_response = json_encode($result);
    echo $mc_response;
} else {
    $mc_response = json_encode($MailChimp->getLastError());
    echo $mc_response;
}

JavaScript

form.addEventListener('submit', (event) => {
    event.preventDefault();
    const url = form.action;
    const formData = new FormData(event.target);

    axios({
        method: 'POST',
        url: url,
        data: formData,
        config: { headers: {'Content-Type': 'multipart/form-data' }}
    })
        .then(function (response) {
            console.log(response);
        })
        .catch(function (response) {
            console.log(response);
        });
});

0 个答案:

没有答案