I'm designing a web page which checks if an email specified is available is database. If it is available, then i must stop submitting the form.
I used ajax for live checking of email and update the response as a span message. If i click submit button, even though the email is already available in the db, the form is submitted and getting redirected to another page. Please do help me get out of this. Thanks in advance.
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script type="text/javascript">
function checkemail() {
var email=document.getElementById( "UserEmail" ).value;
if(email) {
$.ajax({
type: 'post',
url: 'check.php',
data: {
user_email:email,
},
success: function (response) {
$( '#email_status' ).html(response);
}
});
}
}
function validateForm(){
var a=document.getElementById("email_status").innerHTML;
var b="Email Already Exist";
if(a==b)
alert('Yes');
else
alert('No');
}
</script>
</head>
<body>
<form method="POST" action="insertdata.php" onsubmit="return validateForm();">
<input type="text" name="useremail" id="UserEmail" onkeyup="checkemail();">
<span id="email_status"></span><br>
<input type="submit" name="submit_form" value="Submit">
</form>
Expected result when i give an email which is already in db:
Yes.
Actual result:
No
You code has design problems.
1.The biggest one is that you are make an ajax call request while user is typing, that will probably cause you big overhead.
2. the same design is causing the validation not working properly.
Allow me to make a proposal.
<form method="POST" action="insertdata.php" id="form" onsubmit="return false;">
<input type="text" name="useremail" id="UserEmail" >
<span id="email_status"></span><br>
<input type="submit" name="submit_form" value="Submit" onClick="checkemail();">
</form>
in this approach i have removed the keyup event form the input and have added the function checkemail() on button click.
var emails = [];
function checkemail() {
var email = document.getElementById('UserEmail').value;
if (email) {
if (!emails.includes(email)) {
$.ajax({
type: 'post',
url: 'check.php',
data: {
user_email: email,
},
success: function (response) {
$('#email_status').html(response);
if (response == 'Email Already Exist') {
console.log("email "+email+" is a spam")
emails.push(email);
} else {
document.getElementById('form').setAttribute('onsubmit', 'return true;');
document.getElementById('form').submit;
}
}
});
}else{
console.log("email "+email+" is a spam")
}
}
}
In this design approach code does
1.on button click executes checkemail function
2.checkemail function checks the emails array if contains the email from the text input, if the email is in the array then a log is written in console, if not then an ajax requset is done.
3.if the email is in the db then an other log is made, else the form is submitted.
This approach provides the ability of keeping every email that the user will possible write. I also suggest your ajax script instead of returning a text message to return a code maybe 0 or 1, that way comparison is safer.
Last but not least, although i don't know where you intend to use that code please keep in mind that a bot will probably bypass this java script code and hit directly your server side script. So you should think of a server side check also.
If you need more help or clarifications don't hesitate to ask.
Related
This should be simple, yet it's driving me crazy. I have an html5 form that I am submitting with ajax. If you enter an invalid value, there is a popup response that tells you so. How can I check that the entries are valid before I run my ajax submit?
form:
<form id="contactForm" onsubmit="return false;">
<label for="name">Name:</label>
<input type="text" name="name" id="name" required placeholder="Name" />
<label for="subject">Subject:</label>
<input type="text" name="subject" id="subject" required placeholder="Subject" />
<label for="email">Email:</label>
<input type="email" name="email" id="email" required placeholder="email#example.com" />
<label for="message">Message:</label>
<textarea name="message" id="message" required></textarea>
<input type="submit" id="submit"/>
</form>
submit:
$('#submit').click(function(){
var name = $("input#name").val();
var subject = $("input#subject").val();
var email = $("input#email").val();
var message = $("input#message").val();
var dataString = 'email=' + email + '&message=' + message + '&subject=' + subject + '&name=' + name ;
$.ajax({
url: "scripts/mail.php",
type: 'POST',
data: dataString,
success: function(msg){
disablePopupContact();
$("#popupMessageSent").css("visibility", "visible");
},
error: function() {
alert("Bad submit");
}
});
});
If you bind to the submit event instead of click it will only fire if it passes the HTML5 validation.
It is best practice to cache your jQuery selectors in variables if you use it multiple times so you don't have to navigate the DOM each time you access an element. jQuery also provides a .serialize() function that will handle the form data parsing for you.
var $contactForm = $('#contactForm');
$contactForm.on('submit', function(ev){
ev.preventDefault();
$.ajax({
url: "scripts/mail.php",
type: 'POST',
data: $contactForm.serialize(),
success: function(msg){
disablePopupContact();
$("#popupMessageSent").css("visibility", "visible");
},
error: function() {
alert("Bad submit");
}
});
});
By default, jQuery doesn't know anything about the HTML5 validation, so you'd have to do something like:
$('#submit').click(function(){
if($("form")[0].checkValidity()) {
//your form execution code
}else console.log("invalid form");
});
If you are using HTML5 form validation you'll have to send the ajax request in the form's submit handler. The submit handler will only trigger if the form validates. What you're using is a button click handler which will always trigger because it has no association with form validation. NOTE: not all browsers support html5 form validation.
I prefer using the jQuery submit handler, you will still get the response to your form with the following method.
jQuery('#contactForm').on('submit', function (e) {
if (document.getElementById("contactForm").checkValidity()) {
e.preventDefault();
jQuery.ajax({
url: '/some/url',
method: 'POST',
data: jQuery('#contactForm').serialize(),
success: function (response) {
//do stuff with response
}
})
}
return true;
});
Not exactly sure what you mean. But I assume that you want to check in realtime if the input is valid. If so you should use .keyup instead of .click event, because this would lead to an action if the user presses submit. Look at http://api.jquery.com/keyup/
With this you could check the input with every new character insert and display e.g. "not valid" until your validation ist true.
I hope this answers your question!
U can also use jquery validate method to validate form like
$("#form id").validate();
which return boolean value based on form validation & also u can see the error in log using errorList method.
for use above functionality u must include jquery.validate.js file in your script
This should be simple, yet it's driving me crazy. I have an html5 form that I am submitting with ajax. If you enter an invalid value, there is a popup response that tells you so. How can I check that the entries are valid before I run my ajax submit?
form:
<form id="contactForm" onsubmit="return false;">
<label for="name">Name:</label>
<input type="text" name="name" id="name" required placeholder="Name" />
<label for="subject">Subject:</label>
<input type="text" name="subject" id="subject" required placeholder="Subject" />
<label for="email">Email:</label>
<input type="email" name="email" id="email" required placeholder="email#example.com" />
<label for="message">Message:</label>
<textarea name="message" id="message" required></textarea>
<input type="submit" id="submit"/>
</form>
submit:
$('#submit').click(function(){
var name = $("input#name").val();
var subject = $("input#subject").val();
var email = $("input#email").val();
var message = $("input#message").val();
var dataString = 'email=' + email + '&message=' + message + '&subject=' + subject + '&name=' + name ;
$.ajax({
url: "scripts/mail.php",
type: 'POST',
data: dataString,
success: function(msg){
disablePopupContact();
$("#popupMessageSent").css("visibility", "visible");
},
error: function() {
alert("Bad submit");
}
});
});
If you bind to the submit event instead of click it will only fire if it passes the HTML5 validation.
It is best practice to cache your jQuery selectors in variables if you use it multiple times so you don't have to navigate the DOM each time you access an element. jQuery also provides a .serialize() function that will handle the form data parsing for you.
var $contactForm = $('#contactForm');
$contactForm.on('submit', function(ev){
ev.preventDefault();
$.ajax({
url: "scripts/mail.php",
type: 'POST',
data: $contactForm.serialize(),
success: function(msg){
disablePopupContact();
$("#popupMessageSent").css("visibility", "visible");
},
error: function() {
alert("Bad submit");
}
});
});
By default, jQuery doesn't know anything about the HTML5 validation, so you'd have to do something like:
$('#submit').click(function(){
if($("form")[0].checkValidity()) {
//your form execution code
}else console.log("invalid form");
});
If you are using HTML5 form validation you'll have to send the ajax request in the form's submit handler. The submit handler will only trigger if the form validates. What you're using is a button click handler which will always trigger because it has no association with form validation. NOTE: not all browsers support html5 form validation.
I prefer using the jQuery submit handler, you will still get the response to your form with the following method.
jQuery('#contactForm').on('submit', function (e) {
if (document.getElementById("contactForm").checkValidity()) {
e.preventDefault();
jQuery.ajax({
url: '/some/url',
method: 'POST',
data: jQuery('#contactForm').serialize(),
success: function (response) {
//do stuff with response
}
})
}
return true;
});
Not exactly sure what you mean. But I assume that you want to check in realtime if the input is valid. If so you should use .keyup instead of .click event, because this would lead to an action if the user presses submit. Look at http://api.jquery.com/keyup/
With this you could check the input with every new character insert and display e.g. "not valid" until your validation ist true.
I hope this answers your question!
U can also use jquery validate method to validate form like
$("#form id").validate();
which return boolean value based on form validation & also u can see the error in log using errorList method.
for use above functionality u must include jquery.validate.js file in your script
I have an issue I can't seem to solve, I have a form with a bunch of text-fields but I need to extract their information through AJAX or just through a simple JavaScript function. I need this data to be extracted, string by string into an array which should then be passed to PHP. If understood this correctly, AJAX can be used with JQuery or JavaScript, now I'm not sure I understand JQuery very well. Anyway I've been searching google for good examples, and I really can't find anything good.
<form class="registration" method="POST">
<ul class="registration">
<li><label>Nombre de Usuario:</label></li>
<li><input type="text" name="username" title="Nombre de Usuario"/></li>
<li><label>Contraseña:</label></li>
<li><input type="text" name="password" title="Contraseña"/></li>
<li><label>Correo Electrónico:</label></li>
<li><input type="text" name="email" title="Correo Electrónico"/></li>
<li><label>Nombre:</label></li>
<li><input type="text" name="name" title="Nombre"/></li>
<li><label>Primer Apellido:</label></li>
<li><input type="text" name="first last name" title="Primer Apellido"/></li>
<li><label>Segundo Apellido:</label></li>
<li><input type="text" name="second last name" title="Segundo Apellido"/></li>
<li><input type="submit" name="create user" title="Crear Usuario" value="Crear Usuario"></input></li>
</ul>
</form>
This is my form, some of the values are in Spanish, the website I'm supposed to make has to be in that language. If I understood things right, I should call the function I want with an "OnClick" through my submit input button. This is the first time I've done web development, and understanding CSS and HTML was difficult for me. I was wondering if someone could help me out with an example or something. I'm basically using MVC to organize this, with HTML and JavaScript as the View, PHP as the control and Oracle SQL as the model. I'm using PHP precisely for that reason, I need to connect to the database, and send the information through PHP.
I'm not looking for anyone to fix my thing or anything of the sort, all I need is an example and small explanation if possible.
You need to figure out $.ajax function. It easy to implement, and posting the values into your php file, then from there you can processing inserting data into database. Here is sample of code :
$('input[type=submit]').on('click',function(e)
{
e.preventDefault();
var my_username = $('input[name=username]').val();
.....
..... more here
$.ajax({
type : 'POST', //<--- GET or POST
url : 'url_of_insert_process.php',
data : {
username: my_username,
.....
..... more here
}
success : function(data){
// Here you can populate the view whatever you want
// like showing message success
}
});
});
That is the illustration sending the data. You also can use $("form" ).serialize(); to fetch all the form element value using the name that you provided on each html form element. So many sources out there that you can put into your table.
Please try
$(document).ready(function(){
$('input[type="submit"]').click(function(e){
e.preventDefault();
$.ajax({
url: "YOUR_URL",
type: 'POST',
data:$("form#registration").serialize(),
success: function( response ) {
console.log(response);
}
});
});
});
//jsfile.js
//THIS METHOD RETURN THE name : value PAIR FROM
//A SPECIFIED FORM ID OR FORM IN THE CURRENT SPHERE
function formHandler(formID="") {
try {
if (formID === "") {
//PICK UP THE FORM IN THE CURRENT SPHERE
formElms document.querySelectorAll("input,select,textarea");
} else if(formID !== "") {
//PICK UP THE NAMED FORM
var formsElms = document.querySelectorAll("form");
formsElms.forEach(function(formElm) {
if (formElm.id === formID) {
formElms = document.querySelectorAll("#"+formID+" input, #"+formID+" select, #"+formID+" textarea");
}
});
}
if (formElms) {
var retObjs = new Array();
if (formElms) {
formElms.forEach(function(param) {
retObjs.push({name : param.name, value: param.value});
});
}
}
return retObjs;
} catch (e) {
console.log(e);
}
}
serverSideHandler(inda={}) {
try {
indata = inda;
complUrl = "url.php";
$.ajax({
method: "POST",
url: complUrl,
data: indata
})
.done(function(retData) {
serverResponseHandler(retData);//Function To Callback
});
} catch(ev) {
console.log(ev);
}
}
//url.php
<?php
header("Access-Control-Allow-Origin: *");
header('Content-Type: text/json');
ini_set('memory_limit','1024M');
if (!empty($_POST)) {
//Extract your form Inputs as follow
$name = doSomeValidation($_POST['name']);
//Do DB connections
//Do your CRUD
//DO OTHER ACTIONS
}
Okay, so I am trying to use ajax. I've tried several ways of doing this but nothing is working for me. I believe the main problem I have is that ajax won't add to my database, the rest is managable for me.
Here is the relevant ajax-code:
$(document).ready(function(){
console.log($("going to attach submit to:","form[name='threadForm']"));
$("form[name='threadForm']").on("submit",function(e){
e.preventDefault();
var message = $("#message").val();
//assumming validate_post returns true of false(y)
if(!validatepost(message)){
console.log("invalid, do not post");
return;
}
console.log("submitting threadForm");
update_post(message);
});
});
function update_post(message){
var dataString = "message=" + message;
alert(dataString);
$.ajax({
url: 'post_process.php',
async: true,
data: dataString ,
type: 'post',
success: function() {
posts();
}
});
}
function posts(){
console.log("getting url:",sessionStorage.page);
$.get(sessionStorage.page,function(data){
$("#threads").html(data);
});
}
function validatepost(text){
$(document).ready(function(){
var y = $.trim(text);
if (y==null || y=="") {
alert("String is empty");
return false;
} else {
return true;
}
});
}
Here is the post_process.php:
<?php
// Contains sessionStart and the db-connection
require_once "include/bootstrap.php";
$message = $con->real_escape_string($_POST["message"]);
if (validateEmpty($message)){
send();
}
function send(){
global $con, $message;
$con->create_post($_SESSION['username'], $_SESSION['category'], $_SESSION("subject"), $message);
}
//header("Location: index.php");
?>
And lastly, here is the html-form:
<div id="post_div">
<form name="threadForm" method="POST" action="">
<label for="message">Meddelande</label><br>
<textarea id="message" name="message" id="message" maxlength="500">
</textarea><br>
<input type="submit" value="Skicka!" name="post_btn" id="post_btn"><br>
</form>
create_post is a function I've written, it and everything else worked fine until I introduced ajax.
As it is now, none of the console.log:S are getting reached.
Ajax works when jumping between pages on the website but the code above literally does nothing right now. And also, it works if I put post_process.php as the form action and don't comment out the header in post_process-php.
I apologize for forgetting some info. I am tired and just want this to work.
I would first test the update_post by removing the button.submit.onclick and making the form.onsubmit=return update_post. If that is successful place the validate_post in the update_post as a condition, if( !validate_post(this) ){ return false;}
If it's not successful then the problem is in the php.
You also call posts() to do what looks like what $.get would do. You could simply call $.get in the ajax return. I'm not clear what you are trying to accomplish in the "posts" function.
First you can just submit the form to PHP and see if PHP does what it's supposed to do. If so then try to submit using JavaScript:
$("form[name='threadForm']").on("submit",function(e){
e.preventDefault();
//assumming validate_post returns true of false(y)
if(!validate_post()){
console.log("invalid, do not post");
return;
}
console.log("submitting threadForm");
update_post();
});
Press F12 in Chrome or firefox with the firebug plugin installed and see if there are any errors. The POST should show in the console as well so you can inspect what's posted. Note that console.log causes an error in IE when you don't have the console opened (press F12 to open), you should remove the logs if you want to support IE.
Your function posts could use jQuery as well as it makes the code shorter:
function posts(){
console.log("getting url:",sessionStorage.page);
$.get(sessionStorage.page,function(data){
$("#threads").html(data);
});
}
UPDATE
Can you console log if the form is found when you attach the event listener to it?
console.log($("going to attach submit to:","form[name='threadForm']"));
$("form[name='threadForm']").on("submit",function(e){
....
Then set the action of the form to google.com or something to see if the form gets submitted (it should not if the code works). Then check out the console to see the xhr request and see if there are any errors in the request/responses.
Looking at your code it seems you got the post ajax request wrong.
function update_post(message){
console.log(message);
$.ajax({
url: 'post_process.php',
async: true,
//data could be a string but I guess it has to
// be a valid POST or GET string (escape message)
// easier to just let jQuery handle this one
data: {message:message} ,
type: 'post',
success: function() {
posts();
}
});
UPDATE
Something is wrong with your binding to the submit event. Here is an example how it can be done:
<!DOCTYPE html>
<html>
<head>
<script src="the jquery library"></script>
</head>
<body>
<form name="threadForm" method="POST" action="http://www.google.com">
<label for="message">Meddelande</label><br>
<textarea id="message" name="message" id="message" maxlength="500">
</textarea><br>
<input type="submit" value="Skicka!" name="post_btn" id="post_btn"><br>
</form>
<script>
$("form[name='threadForm']").on("submit",function(e){
e.preventDefault();
console.log("message is:",$("#message").val());
});
</script>
</body>
</html>
Even with message having 2 id properties (you should remove one) it works fine, the form is not submitted. Maybe your html is invalid or you are not attaching the event handler but looking at your updated question I think you got how to use document.ready wrong, in my example I don't need to use document.ready because the script accesses the form after the html is loaded, if the script was before the html code that defines the form you should use document ready.
Is there any way to integrate mailchimp simple (one email input) with AJAX, so there is no page refresh and no redirection to default mailchimp page.
This solution doesn't work jQuery Ajax POST not working with MailChimp
Thanks
You don't need an API key, all you have to do is plop the standard mailchimp generated form into your code ( customize the look as needed ) and in the forms "action" attribute change post?u= to post-json?u= and then at the end of the forms action append &c=? to get around any cross domain issue. Also it's important to note that when you submit the form you must use GET rather than POST.
Your form tag will look something like this by default:
<form action="http://xxxxx.us#.list-manage1.com/subscribe/post?u=xxxxx&id=xxxx" method="post" ... >
change it to look something like this
<form action="http://xxxxx.us#.list-manage1.com/subscribe/post-json?u=xxxxx&id=xxxx&c=?" method="get" ... >
Mail Chimp will return a json object containing 2 values: 'result' - this will indicate if the request was successful or not ( I've only ever seen 2 values, "error" and "success" ) and 'msg' - a message describing the result.
I submit my forms with this bit of jQuery:
$(document).ready( function () {
// I only have one form on the page but you can be more specific if need be.
var $form = $('form');
if ( $form.length > 0 ) {
$('form input[type="submit"]').bind('click', function ( event ) {
if ( event ) event.preventDefault();
// validate_input() is a validation function I wrote, you'll have to substitute this with your own.
if ( validate_input($form) ) { register($form); }
});
}
});
function register($form) {
$.ajax({
type: $form.attr('method'),
url: $form.attr('action'),
data: $form.serialize(),
cache : false,
dataType : 'json',
contentType: "application/json; charset=utf-8",
error : function(err) { alert("Could not connect to the registration server. Please try again later."); },
success : function(data) {
if (data.result != "success") {
// Something went wrong, do something to notify the user. maybe alert(data.msg);
} else {
// It worked, carry on...
}
}
});
}
Based on gbinflames' answer, I kept the POST and URL, so that the form would continue to work for those with JS off.
<form class="myform" action="http://XXXXXXXXXlist-manage2.com/subscribe/post" method="POST">
<input type="hidden" name="u" value="XXXXXXXXXXXXXXXX">
<input type="hidden" name="id" value="XXXXXXXXX">
<input class="input" type="text" value="" name="MERGE1" placeholder="First Name" required>
<input type="submit" value="Send" name="submit" id="mc-embedded-subscribe">
</form>
Then, using jQuery's .submit() changed the type, and URL to handle JSON repsonses.
$('.myform').submit(function(e) {
var $this = $(this);
$.ajax({
type: "GET", // GET & url for json slightly different
url: "http://XXXXXXXX.list-manage2.com/subscribe/post-json?c=?",
data: $this.serialize(),
dataType : 'json',
contentType: "application/json; charset=utf-8",
error : function(err) { alert("Could not connect to the registration server."); },
success : function(data) {
if (data.result != "success") {
// Something went wrong, parse data.msg string and display message
} else {
// It worked, so hide form and display thank-you message.
}
}
});
return false;
});
You should use the server-side code in order to secure your MailChimp account.
The following is an updated version of this answer which uses PHP:
The PHP files are "secured" on the server where the user never sees them yet the jQuery can still access & use.
1) Download the PHP 5 jQuery example here...
http://apidocs.mailchimp.com/downloads/mcapi-simple-subscribe-jquery.zip
If you only have PHP 4, simply download version 1.2 of the MCAPI and replace the corresponding MCAPI.class.php file above.
http://apidocs.mailchimp.com/downloads/mailchimp-api-class-1-2.zip
2) Follow the directions in the Readme file by adding your API key and List ID to the store-address.php file at the proper locations.
3) You may also want to gather your users' name and/or other information. You have to add an array to the store-address.php file using the corresponding Merge Variables.
Here is what my store-address.php file looks like where I also gather the first name, last name, and email type:
<?php
function storeAddress(){
require_once('MCAPI.class.php'); // same directory as store-address.php
// grab an API Key from http://admin.mailchimp.com/account/api/
$api = new MCAPI('123456789-us2');
$merge_vars = Array(
'EMAIL' => $_GET['email'],
'FNAME' => $_GET['fname'],
'LNAME' => $_GET['lname']
);
// 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 = "123456a";
if($api->listSubscribe($list_id, $_GET['email'], $merge_vars , $_GET['emailtype']) === true) {
// It worked!
return 'Success! Check your inbox or spam folder for a message containing a confirmation link.';
}else{
// An error ocurred, return error message
return '<b>Error:</b> ' . $api->errorMessage;
}
}
// If being called via ajax, autorun the function
if($_GET['ajax']){ echo storeAddress(); }
?>
4) Create your HTML/CSS/jQuery form. It is not required to be on a PHP page.
Here is something like what my index.html file looks like:
<form id="signup" action="index.html" method="get">
<input type="hidden" name="ajax" value="true" />
First Name: <input type="text" name="fname" id="fname" />
Last Name: <input type="text" name="lname" id="lname" />
email Address (required): <input type="email" name="email" id="email" />
HTML: <input type="radio" name="emailtype" value="html" checked="checked" />
Text: <input type="radio" name="emailtype" value="text" />
<input type="submit" id="SendButton" name="submit" value="Submit" />
</form>
<div id="message"></div>
<script src="jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function() {
$('#signup').submit(function() {
$("#message").html("<span class='error'>Adding your email address...</span>");
$.ajax({
url: 'inc/store-address.php', // proper url to your "store-address.php" file
data: $('#signup').serialize(),
success: function(msg) {
$('#message').html(msg);
}
});
return false;
});
});
</script>
Required pieces...
index.html constructed as above or similar. With jQuery, the appearance and options are endless.
store-address.php file downloaded as part of PHP examples on Mailchimp site and modified with your API KEY and LIST ID. You need to add your other optional fields to the array.
MCAPI.class.php file downloaded from Mailchimp site (version 1.3 for PHP 5 or version 1.2 for PHP 4). Place it in the same directory as your store-address.php or you must update the url path within store-address.php so it can find it.
For anyone looking for a solution on a modern stack:
import jsonp from 'jsonp';
import queryString from 'query-string';
// formData being an object with your form data like:
// { EMAIL: 'emailofyouruser#gmail.com' }
jsonp(`//YOURMAILCHIMP.us10.list-manage.com/subscribe/post-json?u=YOURMAILCHIMPU&${queryString.stringify(formData)}`, { param: 'c' }, (err, data) => {
console.log(err);
console.log(data);
});
Based on gbinflames' answer, this is what worked for me:
Generate a simple mailchimp list sign up form , copy the action URL and method (post) to your custom form. Also rename your form field names to all capital ( name='EMAIL' as in original mailchimp code, EMAIL,FNAME,LNAME,... ), then use this:
$form=$('#your-subscribe-form'); // use any lookup method at your convenience
$.ajax({
type: $form.attr('method'),
url: $form.attr('action').replace('/post?', '/post-json?').concat('&c=?'),
data: $form.serialize(),
timeout: 5000, // Set timeout value, 5 seconds
cache : false,
dataType : 'jsonp',
contentType: "application/json; charset=utf-8",
error : function(err) { // put user friendly connection error message },
success : function(data) {
if (data.result != "success") {
// mailchimp returned error, check data.msg
} else {
// It worked, carry on...
}
}
As for this date (February 2017), it seems that mailchimp has integrated something similar to what gbinflames suggests into their own javascript generated form.
You don't need any further intervention now as mailchimp will convert the form to an ajax submitted one when javascript is enabled.
All you need to do now is just paste the generated form from the embed menu into your html page and NOT modify or add any other code.
This simply works. Thanks MailChimp!
Use jquery.ajaxchimp plugin to achieve that. It's dead easy!
<form method="post" action="YOUR_SUBSCRIBE_URL_HERE">
<input type="text" name="EMAIL" placeholder="e-mail address" />
<input type="submit" name="subscribe" value="subscribe!" />
<p class="result"></p>
</form>
JavaScript:
$(function() {
$('form').ajaxChimp({
callback: function(response) {
$('form .result').text(response.msg);
}
});
})
This Github code works perfectly for me. This has a detailed explanation of how to use it. I use it on my WP site. Here is the link -
https://gist.github.com/DmitriyRF/34f659dbbc02637cf7465e2efdd37ef5
In the other hand, there is some packages in AngularJS which are helpful (in AJAX WEB):
https://github.com/cgarnier/angular-mailchimp-subscribe
I wasn't able to get this working with fetch so had to combine a few answers here using GET and parsing form inputs into the query string for the URL. It also wasn't necessary for the name of the input to be EMAIL but I guess it makes it more legible and doesn't break the code (in this simple case. Play around if you have other form fields).
Here's my code;
<form action="https://me.usxx.list-manage.com/subscribe/post-json?" id="signup" method="GET">
<input type="hidden" name="u" value="xxxxxxxxxxxxxxxxxx"/>
<input type="hidden" name="id" value="xxxxxxxxx"/>
<input type="hidden" name="c" value="?"/>
<input name="EMAIL" type="text" />
</form>
// Form submission handler
const formData = new FormData(signup);
fetch(signup.action + new URLSearchParams(formData).toString(), {
mode: 'no-cors',
method: signup.method,
})
.then((res) => {
// Success
})
.catch((e) => {
// Error
})
You could make it no-js friendly with...
<form action="https://me.usxx.list-manage.com/subscribe/post" id="signup">
fetch(signup.action + '-json?' + new URLSearchParams(formData).toString(), {
And just to save those who fumbled around as I did needlessly, you must create a signup form for an Audience within Mailchimp and by visiting that page you can get your u value and id as well as the action. Maybe this was just me but I thought that wasn't explicitly clear.