Some beginner help needed if anybody can..
I’m writing a contact form with a checkbox to signup to a MailChimp list.
I’m trying to write a JQuery script that checks if the ‘signup’ checkbox is checked then posts the form data to 2 separate PHP scripts – one which posts the data to the MailChimp list and another which sends an email with the forms contents.
How do I:
- Check if the checkbox is selected, then if selected:
- Post the data to the two scripts – but only display the success after BOTH scripts have completed
Currently the script I have works, but ignores the checkbox and displays the success message even if the first script is still processing.
Here’s what I have (edited for clarity) – I’d like to wrap this in an IF statement and then chain the ajax posts together THEN display eh success message
(Ive just thought: Am I right in saying the success part of the ajax call has no idea if the PHP part completed successfully? It just returns success if it sends the data of the the scripts ok? If I wanted to wait until the PHP scripts returned a success is it best to just put in a time delay to give them chance to run before displaying the success message?)
Many thanks for any help!
//check if signup checkbox is checked
if ($('#signup').is(':checked')){
var callOneSuccess, callTwoSuccess;
$(function(){
$.ajax({
type: "POST",
url: "bin/enquiry_process.php",
data: 'name=' + name + '&email=' + email + '&phone=' + phone + '&message=' + message + '&signup=' + signup,
success: function(){
callOneSuccess = true;
bothAjaxCallsComplete();
}
});
$.ajax({
type: "POST",
url: "bin/addtomailchimp.php",
data: 'name=' + name + '&email=' + email,
success: function(){
callOneSuccess = true;
bothAjaxCallsComplete();
}
});
}
function bothAjaxCallsComplete()
{
if(callOneSuccess == true && callTwoSuccess == true)
{
// fade out loading icon
$('.loadericon').fadeOut(1000);
// get height of the the form container then apply it to the css so it doesn't collapse when the form fades out
var formHeight = $('.form_wrap').height();
$('.form_wrap').css('height', formHeight + 'px');
// fadeOut contact form
$('#contactform').fadeOut('slow', function() {
//fadeIn success message
$('#send_success').fadeIn('slow');
});
}
}else{
//do something else.
}
I believe since you have two asynchronous calls you will need to take a look at the global jquery ajax events.
one of them triggers when ALL ajax functions have stopped, conveniently named
.ajaxStop();however just putting your function in there is not going to work out of the box. it does not say your call was successful or not, that is something you would need to workaround.
another option would be to call a function from both success callbacks
both ajax calls are asynchronous, your own third function will just test if both have been successful and the do your stuff… if only 1 call was ready and calls the third function it would not continue because both booleans were not
trueyet.