I use the jQuery ajax function to send data to 2 php scripts. The first script inserts the received data into a MySQL db, the second sends emails. The ajax functions are attached to a click event. For some unknown reason sometimes there are 2 or 3 database entries and sent emails even if I click only once. As you can see the 2nd ajax call is embedded into the first one. I tried to use them in parallel. Tried without ‘set timeout’-s. I also use here the simplemodal plugin. When the first modal closes, the second opens.
Is there a way to make sure that the click event is triggered only once or to block the ajax requests after 1 successfull call?
Here is a part of the code:
$('#confirm').click(function () {
$('#loading').html("<img style = 'display:inline-block;' src = 'img/loading.gif' />");
var servtype = $('select option:selected').text();
$('#type').text(servtype);
$('#staff_name').text(staff_name);
$('#day_time').text(a);
$('#day_date').text(nap + ', ' + dateText);
$('#type1').text(servtype);
$('#staff_name1').text(staff_name);
$('#day_time1').text(a);
$('#day_date1').text(nap + ', ' + dateText);
var message = $('#message').val();
$.ajax({
type: 'GET',
async: true,
url: 'add_booking.php',
data: 'message=' + message + '&date=' + dateText + '&start_end=' + a + '&personid=' + personid + '&servid=' + servid,
success: function (msg) {
var obj = jQuery.parseJSON(msg);
alert('' + obj.answer);
setTimeout(function () {
$.ajax({
type: 'GET',
async: true,
url: 'send_email.php',
data: 'email=zolkazlk@gmail.com&type=' + servtype + '&person=' + staff_name + '&time=' + a + '&date=' + nap + ', ' + dateText,
success: function (msg) {
var obj = jQuery.parseJSON(msg);
alert('' + obj.answer);
$.modal.close();
window.setTimeout(function () {
jQuery('#receipt').modal()
}, 50);
}
});
}, 200);
}
});
});
Finally, in your success call back you can
$('#confirm').die('click')it again.This solution makes you sure that there’s no any other unwanted event raising. I’m using this solution, because high safety. No doubt that it’s better to fix the problem instead of such hacks, but sometimes it’s very time consuming and you don’t like to trace your team member codes.