Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
mailchimp ajax signup form example
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script src="jquery.ketchup.all.min.js" type="text/javascript"></script>
</head>
<body>
<div id="email">
<span>Enter your email to sign up</span>
<form action="/subscribe.php" id="invite" method="POST">
<input type="text" placeholder="your@email.com" name="email" id="address" data-validate="validate(required, email)"/>
<button type="submit">&#187;</button>
</form>
<span id="result"></span>
</div>
<script type="text/javascript">
$(document).ready(function() {
$('#invite').ketchup().submit(function() {
if ($(this).ketchup('isValid')) {
var action = $(this).attr('action');
$.ajax({
url: action,
type: 'POST',
data: {
email: $('#address').attr('value')
},
success: function(data){
$('#result').html(data).css('color', 'green');
},
error: function() {
$('#result').html('Sorry, an error occurred.').css('color', 'red');
}
});
}
return false;
});
});
</script>
</body>
</html>
<?php
$apiKey = 'your-api-key';
$listId = 'your-list-id';
$double_optin=false;
$send_welcome=false;
$email_type = 'html';
$email = $_POST['email'];
//replace us2 with your actual datacenter
$submit_url = "http://us2.api.mailchimp.com/1.3/?method=listSubscribe";
$data = array(
'email_address'=>$email,
'apikey'=>$apiKey,
'id' => $listId,
'double_optin' => $double_optin,
'send_welcome' => $send_welcome,
'email_type' => $email_type
);
$payload = json_encode($data);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $submit_url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, urlencode($payload));
$result = curl_exec($ch);
curl_close ($ch);
$data = json_decode($result);
if ($data->error){
echo $data->error;
} else {
echo "Got it, you've been added to our email list.";
}
@dstello

This comment has been minimized.

Show comment Hide comment
@dstello

dstello Feb 27, 2013

this is awesome!
can i just add fields to $data to match my list?

dstello commented Feb 27, 2013

this is awesome!
can i just add fields to $data to match my list?

@fcaivano

This comment has been minimized.

Show comment Hide comment
@fcaivano

fcaivano Mar 9, 2013

I keep getting "You must specify a email_address value for the listSubscribe method"

any ideas?

fcaivano commented Mar 9, 2013

I keep getting "You must specify a email_address value for the listSubscribe method"

any ideas?

@Klaasie

This comment has been minimized.

Show comment Hide comment
@Klaasie

Klaasie Mar 21, 2013

To fix the "You must specify a email_address value for the listSubscribe method", change $('#address').attr('value') to $('#address').val().

Klaasie commented Mar 21, 2013

To fix the "You must specify a email_address value for the listSubscribe method", change $('#address').attr('value') to $('#address').val().

@tpechacek

This comment has been minimized.

Show comment Hide comment
@tpechacek

tpechacek Apr 3, 2013

This has been a HUGE help! However, I am still having trouble using the AJAX quality. It still goes to another page and loads my .php file. I want to keep it on the same page without changing/refresh.

Any ideas?

Thanks in advance

This has been a HUGE help! However, I am still having trouble using the AJAX quality. It still goes to another page and loads my .php file. I want to keep it on the same page without changing/refresh.

Any ideas?

Thanks in advance

@stefsullrew

This comment has been minimized.

Show comment Hide comment
@stefsullrew

stefsullrew Apr 5, 2013

Hey tpechacek - did you change the setting within the Mailchimp admin to go to your site's thank you page? We used a hash url— www.mysite.com/#thankyou — and told Mailchimp to use that (In the — Signup "thank you" page email area). It slides a thankyou panel in when the form successfully submits, but stays on the same page.

Hey tpechacek - did you change the setting within the Mailchimp admin to go to your site's thank you page? We used a hash url— www.mysite.com/#thankyou — and told Mailchimp to use that (In the — Signup "thank you" page email area). It slides a thankyou panel in when the form successfully submits, but stays on the same page.

@Nyctophilic

This comment has been minimized.

Show comment Hide comment
@Nyctophilic

Nyctophilic Apr 11, 2013

THANK YOU, GREAT HELP!

I'm facing the same problem with tpechacek...the php file loads and shows the result.

THANK YOU, GREAT HELP!

I'm facing the same problem with tpechacek...the php file loads and shows the result.

@kerns

This comment has been minimized.

Show comment Hide comment
@kerns

kerns Apr 14, 2013

I made the change suggested by @Klaasie ...but now it throws "You must specify a email_address value for the listSubscribe method"... any ideas?

kerns commented Apr 14, 2013

I made the change suggested by @Klaasie ...but now it throws "You must specify a email_address value for the listSubscribe method"... any ideas?

@jrcarb

This comment has been minimized.

Show comment Hide comment
@jrcarb

jrcarb Apr 15, 2013

@kerns - same here... I still get "You must specify a email_address value for the listSubscribe method" even after changing the email to $('#address').val(). Here is my code (modified for additional fields)

$(document).ready(function() {
                    $('#invite').ketchup().submit(function() {
                        if ($(this).ketchup('isValid')) {                                       
                            var action = $(this).attr('action');
                                $.ajax({
                                        url: action,
                                        type: 'POST',
                                        data: {
                                        email: $('#pty_email_contest').val(),
                                        fname: $('#pty_fname').val(),
                                        lname: $('#pty_lname').val(),                                       
                                        city: $('#pty_city').val(),
                                        state: $('#pty_state').val(),
                                        bday: $('#pty_birthday').val()

                                    },                                  
                                    success: function(data){
                                        $('#result').html(data);
                                    },
                                    error: function() {
                                        $('#result').html('Sorry, an error occurred.').css('color', 'red');
                                    }
                                });
                        }
                        return false;
                    });
                });

**************** MY SUBSCRIBE.PHP FILE ****************

<?php
$apiKey = 'XXXxx';
$listId = 'XXXxx';
$double_optin=false;
$send_welcome=false;
$email_type = 'html';
$email = $_POST['email'];
$fname = $_POST['fname'];
$lname = $_POST['lname'];
$city = $_POST['city'];
$state = $_POST['state'];
$bday = $_POST['bday'];
//replace us2 with your actual datacenter
$submit_url = "http://us4.api.mailchimp.com/1.3/?method=listSubscribe";
$data = array(
'email_address'=>$email,
'merge_vars' => array('FNAME'=>$fname, 'LNAME'=>$lname, 'CITY'=>$city, 'STATE'=>$state, 'BIRTHDAY'=>$bday),
'apikey'=>$apiKey,
'id' => $listId,
'double_optin' => $double_optin,
'send_welcome' => $send_welcome,
'email_type' => $email_type
);
$payload = json_encode($data);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $submit_url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, urlencode($payload));
$result = curl_exec($ch);
curl_close ($ch);
$data = json_decode($result);
if ($data->error){
    echo $data->error;
} else {
    echo "Got it, you've been added to our email list.";
}
?>

Any help would be greatly appreciated.

jrcarb commented Apr 15, 2013

@kerns - same here... I still get "You must specify a email_address value for the listSubscribe method" even after changing the email to $('#address').val(). Here is my code (modified for additional fields)

$(document).ready(function() {
                    $('#invite').ketchup().submit(function() {
                        if ($(this).ketchup('isValid')) {                                       
                            var action = $(this).attr('action');
                                $.ajax({
                                        url: action,
                                        type: 'POST',
                                        data: {
                                        email: $('#pty_email_contest').val(),
                                        fname: $('#pty_fname').val(),
                                        lname: $('#pty_lname').val(),                                       
                                        city: $('#pty_city').val(),
                                        state: $('#pty_state').val(),
                                        bday: $('#pty_birthday').val()

                                    },                                  
                                    success: function(data){
                                        $('#result').html(data);
                                    },
                                    error: function() {
                                        $('#result').html('Sorry, an error occurred.').css('color', 'red');
                                    }
                                });
                        }
                        return false;
                    });
                });

**************** MY SUBSCRIBE.PHP FILE ****************

<?php
$apiKey = 'XXXxx';
$listId = 'XXXxx';
$double_optin=false;
$send_welcome=false;
$email_type = 'html';
$email = $_POST['email'];
$fname = $_POST['fname'];
$lname = $_POST['lname'];
$city = $_POST['city'];
$state = $_POST['state'];
$bday = $_POST['bday'];
//replace us2 with your actual datacenter
$submit_url = "http://us4.api.mailchimp.com/1.3/?method=listSubscribe";
$data = array(
'email_address'=>$email,
'merge_vars' => array('FNAME'=>$fname, 'LNAME'=>$lname, 'CITY'=>$city, 'STATE'=>$state, 'BIRTHDAY'=>$bday),
'apikey'=>$apiKey,
'id' => $listId,
'double_optin' => $double_optin,
'send_welcome' => $send_welcome,
'email_type' => $email_type
);
$payload = json_encode($data);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $submit_url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, urlencode($payload));
$result = curl_exec($ch);
curl_close ($ch);
$data = json_decode($result);
if ($data->error){
    echo $data->error;
} else {
    echo "Got it, you've been added to our email list.";
}
?>

Any help would be greatly appreciated.

@kerns

This comment has been minimized.

Show comment Hide comment
@kerns

kerns Apr 16, 2013

Any ideas @mfkp? ...@Klaasie? ...Bueller?

kerns commented Apr 16, 2013

Any ideas @mfkp? ...@Klaasie? ...Bueller?

@Nyctophilic

This comment has been minimized.

Show comment Hide comment
@Nyctophilic

Nyctophilic Apr 17, 2013

@jrcarb

Make sure you're using the "name" attributes correctly in the php. And use a merge_vars to pass the names, address, and whatever according to http://apidocs.mailchimp.com/api/1.3/listsubscribe.func.php
or under the list's "Settings" --> "List Fields and |MERGE| Tags"

Something like

$double_optin=false; $send_welcome=false; $email_type = 'html'; $merge_vars = Array( 'EMAIL' => $_POST['pty_email_contest'], 'MERGE1' => $_POST['pty_fname'], );

$data = array(
'apikey'=>$apiKey,
'id' => $listId,
'double_optin' => $double_optin,
'send_welcome' => $send_welcome,
'email_type' => $email_type,
'merge_vars' => $merge_vars
);

@jrcarb

Make sure you're using the "name" attributes correctly in the php. And use a merge_vars to pass the names, address, and whatever according to http://apidocs.mailchimp.com/api/1.3/listsubscribe.func.php
or under the list's "Settings" --> "List Fields and |MERGE| Tags"

Something like

$double_optin=false; $send_welcome=false; $email_type = 'html'; $merge_vars = Array( 'EMAIL' => $_POST['pty_email_contest'], 'MERGE1' => $_POST['pty_fname'], );

$data = array(
'apikey'=>$apiKey,
'id' => $listId,
'double_optin' => $double_optin,
'send_welcome' => $send_welcome,
'email_type' => $email_type,
'merge_vars' => $merge_vars
);

@jrcarb

This comment has been minimized.

Show comment Hide comment
@jrcarb

jrcarb Apr 17, 2013

@mfkp @Nyctophilic - Seems like this might be a browser issue ... I was able to get the script to work the way I want in Firefox, but Safari submits to a different page and also still shows the error "You must specify a email_address value for the listSubscribe method". In Firefox however, the form stays on the same page and submits to the correct signup list with no errors and works fine. Not sure if this has to do with the jQuery? Anyone else have this issue?

jrcarb commented Apr 17, 2013

@mfkp @Nyctophilic - Seems like this might be a browser issue ... I was able to get the script to work the way I want in Firefox, but Safari submits to a different page and also still shows the error "You must specify a email_address value for the listSubscribe method". In Firefox however, the form stays on the same page and submits to the correct signup list with no errors and works fine. Not sure if this has to do with the jQuery? Anyone else have this issue?

@jrcarb

This comment has been minimized.

Show comment Hide comment
@jrcarb

jrcarb Apr 19, 2013

@kerns - ended up going with an alternate method to accomplish the jQuery submission with the MailChimp API - I can send you the files if you need them. It is cross browser compatible and submits quickly via the API. Also, thank you to @Nyctophilic for your help and support.

jrcarb commented Apr 19, 2013

@kerns - ended up going with an alternate method to accomplish the jQuery submission with the MailChimp API - I can send you the files if you need them. It is cross browser compatible and submits quickly via the API. Also, thank you to @Nyctophilic for your help and support.

@Nyctophilic

This comment has been minimized.

Show comment Hide comment
@Nyctophilic

Nyctophilic Apr 20, 2013

@jrcarb ...glad to help.

I'm interested in your jQuery solution, I can't seem to get it to work without a page reload.

@jrcarb ...glad to help.

I'm interested in your jQuery solution, I can't seem to get it to work without a page reload.

@pitrik

This comment has been minimized.

Show comment Hide comment
@pitrik

pitrik May 7, 2013

@jrcarb I would also be interested in how you managed this, if you're willing to share.

pitrik commented May 7, 2013

@jrcarb I would also be interested in how you managed this, if you're willing to share.

@pdquint

This comment has been minimized.

Show comment Hide comment
@pdquint

pdquint Jun 17, 2013

@stefsullrew can tell me a brief how to create thanks page in mailchimp. I tried to create thanks page through mailchimp but can't get the option there..
Im using mailchimp API for wordpress. I created a sign up page using mailchimp API but facing problem that after signup the page will go to home page or another thans page. waiting for your reply @stefsullrew.

pdquint commented Jun 17, 2013

@stefsullrew can tell me a brief how to create thanks page in mailchimp. I tried to create thanks page through mailchimp but can't get the option there..
Im using mailchimp API for wordpress. I created a sign up page using mailchimp API but facing problem that after signup the page will go to home page or another thans page. waiting for your reply @stefsullrew.

@pdquint

This comment has been minimized.

Show comment Hide comment
@pdquint

pdquint Jun 17, 2013

@mfkp your code is not working ...

pdquint commented Jun 17, 2013

@mfkp your code is not working ...

@surjithctly

This comment has been minimized.

Show comment Hide comment
@surjithctly

surjithctly Oct 16, 2013

I got the same error "You must specify a email_address value for the listSubscribe method"

Klaasie, Your Fix worked like a charm... Great!!

change $('#address').attr('value') to $('#address').val().

Admin, please add it to your code also.

I got the same error "You must specify a email_address value for the listSubscribe method"

Klaasie, Your Fix worked like a charm... Great!!

change $('#address').attr('value') to $('#address').val().

Admin, please add it to your code also.

@perminna

This comment has been minimized.

Show comment Hide comment
@perminna

perminna Feb 13, 2014

Thank you! Worked like a charm after the $('#address').attr('value') -> $('#address').val() update.

Thank you! Worked like a charm after the $('#address').attr('value') -> $('#address').val() update.

@Cam

This comment has been minimized.

Show comment Hide comment
@Cam

Cam Mar 25, 2014

I too was having the issue where users are redirected to the PHP page on submit, rather than the AJAX live updating the page. Then a bit of debugging showed that I had simply failed to load ketchup. Easy to miss, but very important!

Cam commented Mar 25, 2014

I too was having the issue where users are redirected to the PHP page on submit, rather than the AJAX live updating the page. Then a bit of debugging showed that I had simply failed to load ketchup. Easy to miss, but very important!

@ibrent

This comment has been minimized.

Show comment Hide comment
@ibrent

ibrent Apr 17, 2014

Thanks. Yes it worked but I made four small but important changes:

  1. Made sure the "subscribe.php" file is in the right spot since that first slash ("/subscribe.php") of your form action will go to the top of the stack, yo. This is in the index.html file. I removed the slash to make it relative.
  2. Added the latest ketchup.js file which I downloaded from here:
    https://github.com/mustardamus/ketchup-plugin/downloads
  3. Fixed .val() code change listed above on line 25 of index.html
    $('#address').attr('value') should be changed to $('#address').val()
  4. Then I got this error in my browser console "event.returnValue is deprecated. Please use the standard event.preventDefault() instead.". And I was like, "say what??!!"
    For that fix, I simply made sure I was using the latest or a later version of Jquery:
    script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script

Boom. Bob's your uncle. Or that's how the saying goes at least. All works splendidly now. Rawk. Thank you all.

ibrent commented Apr 17, 2014

Thanks. Yes it worked but I made four small but important changes:

  1. Made sure the "subscribe.php" file is in the right spot since that first slash ("/subscribe.php") of your form action will go to the top of the stack, yo. This is in the index.html file. I removed the slash to make it relative.
  2. Added the latest ketchup.js file which I downloaded from here:
    https://github.com/mustardamus/ketchup-plugin/downloads
  3. Fixed .val() code change listed above on line 25 of index.html
    $('#address').attr('value') should be changed to $('#address').val()
  4. Then I got this error in my browser console "event.returnValue is deprecated. Please use the standard event.preventDefault() instead.". And I was like, "say what??!!"
    For that fix, I simply made sure I was using the latest or a later version of Jquery:
    script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script

Boom. Bob's your uncle. Or that's how the saying goes at least. All works splendidly now. Rawk. Thank you all.

@prosenjeet

This comment has been minimized.

Show comment Hide comment
@prosenjeet

prosenjeet Apr 21, 2014

The script works for me only that I had to remove the '/' before subscribe.php as suggested by ibrent above.
Is there any way we can make this system populate the First name, Last name and Country in mailchimp data?

The script works for me only that I had to remove the '/' before subscribe.php as suggested by ibrent above.
Is there any way we can make this system populate the First name, Last name and Country in mailchimp data?

@supriyaphalne

This comment has been minimized.

Show comment Hide comment
@supriyaphalne

supriyaphalne Oct 15, 2014

Hello,
Can anyone help me for this...this code is working fine when i am running it on localhost, and for online package it is working for homepage only....am I missing anything ,..please help me for this.

Hello,
Can anyone help me for this...this code is working fine when i am running it on localhost, and for online package it is working for homepage only....am I missing anything ,..please help me for this.

@fheo

This comment has been minimized.

Show comment Hide comment
@fheo

fheo Aug 24, 2015

ajax is not working. The page loads the php file instead of showing the message on the same page

fheo commented Aug 24, 2015

ajax is not working. The page loads the php file instead of showing the message on the same page

@kamiuetian

This comment has been minimized.

Show comment Hide comment
@kamiuetian

kamiuetian Oct 7, 2015

Hi, What i want to do is, Retrieve the email address at confirmation thankyou page?
How can I do that?

Hi, What i want to do is, Retrieve the email address at confirmation thankyou page?
How can I do that?

@SamiAibeche

This comment has been minimized.

Show comment Hide comment
@SamiAibeche

SamiAibeche Jun 28, 2016

Thank's for your help !

Thank's for your help !

@jmccabeVA

This comment has been minimized.

Show comment Hide comment
@jmccabeVA

jmccabeVA Oct 17, 2016

Anyway to get this updated for the mail chimp v3 API? Also, would like to see example that on submit, can redirect to a URL. Just need email. I understand that changing mail chimp value from 'pending' to 'subscribed' will allow you to do single opt-in. Any help would be appreciated.

Anyway to get this updated for the mail chimp v3 API? Also, would like to see example that on submit, can redirect to a URL. Just need email. I understand that changing mail chimp value from 'pending' to 'subscribed' will allow you to do single opt-in. Any help would be appreciated.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment