I'm working to integrate with the MailChimp API to submit a form via Ajax, but I'm having a lot of trouble integrating the form they provide. I think this is a good opportunity for me to learn more about Ajax, but I can't for the life of me figure out where my call is going wrong. Here's what I have in my Ajax call:
$('#submit-button').click(function(){
var email = $('input#email').val();
if(email == "[email protected]"){
$('p#empty-error').fadeIn();
return false;
}
var datastring1 = 'email=' + email;
$.ajax({
type: 'POST',
url: 'mailchimp/store-address.php',
data: datastring1,
success: function(){
alert('success');
}
});
return false;
});
And the PHP file to tag along:
function storeAddress(){
// Validation
if(!$_POST['email']){ return "No email address provided"; }
if(!preg_match("/^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*$/i", $_POST['email'])) {
return "Email address is invalid";
}
require_once('MCAPI.class.php');
// grab an API Key from http://admin.mailchimp.com/account/api/
$api = new MCAPI('66a7f17d87e96e439f7a2837e2963180-us1');
// grab your List's Unique Id by going to http://admin.mailchimp.com/lists/
// Click the "settings" link for the list - the Unique Id is at the bottom of that page.
$list_id = "b1ebe7c0ba";
if($api->listSubscribe($list_id, $_POST['email'], '') === true) {
// It worked!
return 'Success! Check your email to confirm sign up.';
}else{
// An error ocurred, return error message
return 'Error: ' . $api->errorMessage;
}
}
// If being called via ajax, autorun the function
if($_POST['ajax']){ echo storeAddress(); }
?>
The script was originally written to submit via Ajax in Prototype, and I'm trying to move things over to jQuery. I'd love to know what I'm not understanding to make this happen.
More info: If it's any help, the following call works if it's in my HTML if I removed the javascript altogether:
<?php require_once('mailchimp/store-address.php'); if($_POST['submit']){ echo storeAddress(); } ?>