Here is my code which I am using to subscribe users to multiple Mailchimp lists in which they choose and is posted to this file by an ajax request. Here is the code:
So for some reason this returns a success from Mailchimp, but it doesn't actually subscribe to the lists I have entered. I have confirmed the list ids are correct and fields are too.
(I have removed all reference to the actual IDs)
<?php
include 'MailChimp.php';
$mailchimp = new MailChimp('MYAPI_KEY'); //I have my code in here
$newsletter_keyarray = array(
"List one" => "listoneid",
"List two" => "listtwoid",
"List three" => "listthreeid",
"List four" => "listfourid"
);
$any_errors = false;
foreach ($_POST['lists'] as $key => $list) {
if(in_array($list, $newsletter_keyarray)){
$merge_vars_array = array(
'EMAIL' => $_POST['email']
);
if($list == "List one"){
$merge_vars_array['MMERGE1'] = $_POST['fname'];
$merge_vars_array['MMERGE2'] = $_POST['sname'];
$merge_vars_array['MMERGE3'] = $_POST['org'];
}else if($list == "List two"){
$merge_vars_array['FNAME'] = $_POST['fname'];
$merge_vars_array['LNAME'] = $_POST['sname'];
$merge_vars_array['MMERGE4'] = $_POST['job'];
$merge_vars_array['MMERGE5'] = $_POST['org'];
}else if($list == "List three"){
$merge_vars_array['FNAME'] = $_POST['fname'];
$merge_vars_array['LNAME'] = $_POST['sname'];
$merge_vars_array['MMERGE3'] = $_POST['org'];
$merge_vars_array['MMERGE4'] = $_POST['job'];
}else if($list == "List four"){
$merge_vars_array['FNAME'] = $_POST['fname'];
$merge_vars_array['LNAME'] = $_POST['sname'];
$merge_vars_array['MMERGE4'] = $_POST['job'];
$merge_vars_array['MMERGE5'] = $_POST['org'];
}
$mailResults = $mailchimp->call('lists/subscribe', array(
'id' => $newsletter_keyarray[$list],
'email' => array('email' => $_POST['email']),
'merge_vars' => $merge_vars_array,
'double_optin' => false
));
if(isset($mailResults['status']) && $mailResults['status'] == 'error'){
$any_errors = true;
}
}
}
//enter api and userdetails here
$response_array = array();
if($any_errors){
header('Content-type: application/json');
$response_array['status'] = 'error';
if(!filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)){
$response_array['message'] = 'The email you have entered is not valid';
}else if(isset($mailResults['error']) && $mailResults['error'] != ""){
$response_array['message'] = $mailResults['error'];
}
echo json_encode($response_array);
}else{
header('Content-type: application/json');
$response_array['status'] = 'success';
echo json_encode($response_array);
}
?>
I have figured it out kind of stupid of me.
The issue was in_array
which compares the value rather than the key. So in the end I used array_key_exists
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.