使用AJAX的Mailchimp API调用
I am using
error:function(exception){alert('Exception:'+ JSON.stringify(exception));}
to display an exception if there is an AJAX error, and here is the response i get:
Exception:{"readyState":4,"responseText":"","status":200,"statusText":"OK"}
This looks like a successful response to me, but it is the function that is called on error
which means something is going wrong.
Here is the page: http://cuttingedgeconversions.com/free-month.html
I have a successful API call to subscribe a new email address to mail chimp using form action. But I do not want to redirect to another page after form submission, so I took out the 'form action' property and I tried adding this API call to script.js which uses ajax.
Here is the HTML:
<form class="email_form_freemonth" method="post">
<h3>Get your first month free</h3>
<div class="form-group customised-formgroup"> <span class="icon-user"></span>
<input type="text" name="full_name" class="form-control" placeholder="Name">
</div>
<div class="form-group customised-formgroup"> <span class="icon-envelope"></span>
<input type="email" name="email" class="form-control" placeholder="Email">
</div>
<!--<div class="form-group customised-formgroup"> <span class="icon-telephone"></span>
<input type="text" name="phone" class="form-control" placeholder="Phone (optional)">
</div>-->
<div class="form-group customised-formgroup"> <span class="icon-laptop"></span>
<input type="text" name="website" class="form-control" placeholder="Website (optional)">
</div>
<!--<div class="form-group customised-formgroup"> <span class="icon-bubble"></span>
<textarea name="message" class="form-control" placeholder="Message"></textarea>
</div>-->
<div>
<br>
<button style="margin: 0 auto" name="submit" type="submit" class="btn btn-fill full-width">GET FREE MONTH<span class="icon-chevron-right"></span></button>
</div>
</form>
Here is freemonth_action.php (which gets called in script.js, seen below):
<?php
session_start();
if($_SERVER['REQUEST_METHOD'] == "POST"){
$name = trim($_POST['full_name']);
$email = trim($_POST['email']);
if(!empty($email) && !filter_var($email, FILTER_VALIDATE_EMAIL) === false){
// MailChimp API credentials
$apiKey = '*****';
$listID = '0cf013d1d9';
// MailChimp API URL
$memberID = md5(strtolower($email));
$dataCenter = substr($apiKey,strpos($apiKey,'-')+1);
$url = 'https://' . $dataCenter . '.api.mailchimp.com/3.0/lists/' . $listID . '/members/' . $memberID;
// member information
$json = json_encode([
'email_address' => $email,
'status' => 'subscribed',
'merge_fields' => [
'NAME' => $name,
]
]);
// send a HTTP POST request with curl
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_USERPWD, 'user:' . $apiKey);
curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_TIMEOUT, 10);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'PUT');
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, $json);
$result = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
//echo json_decode($result);
// store the status message based on response code
if ($httpCode == 200) {
$_SESSION['msg'] = '<p style="color: #34A853">You have successfully subscribed to CodexWorld.</p>';
} else {
switch ($httpCode) {
case 214:
$msg = 'You are already subscribed.';
break;
default:
$msg = 'Some problem occurred, please try again.';
break;
}
$_SESSION['msg'] = '<p style="color: #EA4335">'.$msg.'</p>';
}
}else{
$_SESSION['msg'] = '<p style="color: #EA4335">Please enter valid email address.</p>';
}
}
I know these are correct because when I used 'form action = scripts/freemonth_action.php'
it works. But I don't want the page to redirect on submission, so I have added an ajax call in my script that gets triggered from script.js. I have 2 ajax calls right now in script.js, the first one is working but the second one is not. The weird part is that BOTH RETURN STATUS CODE 200.
script.js with non-nested Ajax calls - WORKING PROPERLY NOW:
$('.email_form_freemonth').on('submit', function (e) {
e.preventDefault();
var _self = $(this);
var __selector = _self.closest('input,textarea');
_self.closest('div').find('input,textarea').removeAttr('style');
_self.find('.msg').remove();
_self.closest('div').find('button[type="submit"]').attr('disabled', 'disabled');
var data = $(this).serialize();
$.ajax({
url: 'scripts/email_freeMonth.php',
type: "post",
dataType: 'json',
data: data,
success: function (data) {
_self.closest('div').find('button[type="submit"]').removeAttr('disabled');
if (data.code == false) {
_self.closest('div').find('[name="' + data.field + '"]').css('border-bottom', 'solid 2px red');
_self.find('.customised-formgroup').last().after('<div class="msg"><p style="color:red;padding:0;font-size:13px;font-weight:bold;position:absolute">*' + data.err + '</p></div>');
} else {
$('.msg').html('<p style="color:green;padding:0;font-size:13px;font-weight:bold;position:absolute">' + data.success + '</p>');
_self.find('.customised-formgroup').last().after('<div class="msg"><p style="color:green;padding:0;font-size:13px;font-weight:bold;position:absolute">' + data.success + '</p></div>');
_self.closest('div').find('input,textarea').val('');
}
}
});
$.ajax({
url: 'scripts/freemonth_action.php',
type: "post",
dataType: 'json',
data: data,
success: function (data) {
_self.closest('div').find('button[type="submit"]').removeAttr('disabled');
if (data.code == false) {
console.log("DATA.CODE == FALSE");
} else {
console.log("DATA.CODE == TRUE");
}
},
error:function(exception){alert('Exception:'+ JSON.stringify(exception));}
});
});
When you're passing serialized data through the AJAX request, if(isset($_POST['submit']))
won't evaluate as true because the button isn't part of the data being sent through the request. You can use if($_SERVER['REQUEST_METHOD'] == "POST")
instead to check if the request was submitted. Just update that in your PHP file and it should work!
I think you need to add under you first call ajax {} the second call {into}.
$('.email_form_freemonth').on('submit', function (e) {
e.preventDefault();
var _self = $(this);
var __selector = _self.closest('input,textarea');
_self.closest('div').find('input,textarea').removeAttr('style');
_self.find('.msg').remove();
_self.closest('div').find('button[type="submit"]').attr('disabled', 'disabled');
var data = $(this).serialize();
$.ajax({ //WORKS
url: 'scripts/email_freeMonth.php',
type: "post",
dataType: 'json',
data: data,
success: function (data) {
_self.closest('div').find('button[type="submit"]').removeAttr('disabled');
if (data.code == false) {
_self.closest('div').find('[name="' + data.field + '"]').css('border-bottom', 'solid 2px red');
_self.find('.customised-formgroup').last().after('<div class="msg"><p style="color:red;padding:0;font-size:13px;font-weight:bold;position:absolute">*' + data.err + '</p></div>');
} else {
$('.msg').html('<p style="color:green;padding:0;font-size:13px;font-weight:bold;position:absolute">' + data.success + '</p>');
_self.find('.customised-formgroup').last().after('<div class="msg"><p style="color:green;padding:0;font-size:13px;font-weight:bold;position:absolute">' + data.success + '</p></div>');
_self.closest('div').find('input,textarea').val('');
}
}
//because you are under an event submit "form" and you ajax post was after this one
$.ajax({
url: 'scripts/freemonth_action.php',
type: "post",
dataType: 'json',
success: function (data) {
alert(data);
}
});
});
</div>