Ajax- beforeSend - javascript

In order to prevent getting an error twice I use beforeSend.
hasSent = false
function submit() {
if (!hasSent)
$.ajax({
url: "${createLink(controller:'userInvitation', action:'ajaxUpdate')}",
type: "POST",
data: $("#invitationForm").serialize(),
success: function(data, textStatus, jqXHR) {
$('#invitationForm')[0].reset();
$('.thank-you-modal').modal('show');
hasSent = true;
console.log(hasSent)
},
complete: function() {
hasSent = false;
console.log(hasSent)
}
});
}
As you can see the ajax should happen only if hasSent=false.
For some reason the ajax happens also if the user clicks multiple time (very quick) on the submit button

To prevent this kind of issue disable the button before sending the ajax and then anable inside the success function
$(mybutton).prop("disabled",true);
// ajax call here
then
success: function(data, textStatus, jqXHR) {
$(mybutton).prop("disabled",false);
// code here
}

You can create another flag such as isSending
function submit() {
if(isSending)
return;
isSending = true
$.ajax({
// ...
complete: function() {
isSending = false;
}
});
}

there are two ways you can do this.
1) create a flag and check if the button is pressed. If pressed then do not execute the ajax code
change the flag back once the request is successful, like this
success:function(...)
{
flag=false;
}
Or you can disable the button at the button click so the request will be carried out and double click situation won't arise. Enable the button on complete like this
complete:function(..){ $("yourbutton").attr("disabled",false)}

Related

Call ajax on before page unload

I'm trying to call an ajax before user leaving a page, this what i have done so far. But it doesn't even hit the ajax page.
This is what i have done so far.
window.onbeforeunload = closeIt();
function closeIt()
{
var key="save-draft";
$.ajax({
url: "app/ajax_handler.php",
type:"GET",
data:{key:key},
success: function(data) {
return data;
}
});
}
I Have tried this one also both failed in my case.
$( window ).unload(function() {});
The only way I think is to let the user know that it's a process on background with a confirm message, that will block the exit until user click on Accept or you've got the response.
Something like that:
window.onbeforeunload = closeIt();
function closeIt()
{
/*var key="save-draft";
$.ajax({
url: "app/ajax_handler.php",
type:"GET",
data:{key:key},
success: function(data) {
return data;
}
});*/
setTimeout(function() {
return confirm("There is a process that isn't finished yet, you will lose some data. Are you sure you want to exit?");
}, 1000);
}

Jquery - Ajax : Unhandled multiple clicks event with ajax button "on Click method"

I have a button where i'm injecting an ajax request to a distant web service.
the traitment takes effects after checking a condition given from the success of another ajax request (thats why i am usung "ajaxSuccess")
My fonction looks like this :
$('body').on('click', '#btn', function (e) {
$(document).ajaxSuccess(function (event, xhr, settings) {
if (settings.url === window.annonce.route.testService) {
xhr = xhr.responseJSON;
var msg = {},
if (xhr == 1) { //case of traitement to be done
msg["attr1"] = attr1;
msg["attr2"] = attr2;
msg = JSON.stringify(msg);
console.log(msg);
$.ajax({
method: 'POST',
url: servicePostulation,
data: {msg: msg},
dataType: 'json',
success: function (data) {
console.log(data);
$("#btn").addClass("active");
},
error: function (data) {
console.log(data);
}
});
}
}
})
}
I my case , the "console.log(msg)" shows me a multiple sending of data msg , which means a multiple clicking events , and that's exactly the problem i wanna evitate,
i have tried many solutions with the " $('body').on('click') like :
e.stopImmediatePropagation();
e.preventDefault();
stopPropagation()
one()
off()
unbind()
but nothing works , so is there any further solution or explication ??
My suggest is to disable the button when user click and then enable the button when ajax complete.
**onClick:**
$('#btn').prop("disabled", true);
Ajax complete/success:
$('#btn').prop("disabled", false);

Javascript- How to check if operation has been completed on this event

Is there any way to check if the event is completed and element is free to perform another action?
Like I want to do
$('#button-cancel').on('click', function() {
// send ajax call
});
/****************************************
extra code
*******************************************/
$('#button-cancel').on('click', function() {
if(ajax call is completed) {
//do some thing
}
});
I don't want to send ajax call in second onclick as it is already been sent, just want to check if it is done with ajax then do this
You can introduce a helper variable:
// introduce variable
var wasAjaxRun = false;
$('#button-cancel').on('click', function() {
// in ajax complete event you change the value of variable:
$.ajax({
url: "yoururl"
// other parameters
}).done(function() {
// your other handling logic
wasAjaxRun = true;
});
});
$('#button-cancel').on('click', function() {
if(wasAjaxRun === true) {
//do some thing
}
});
EDIT: I just noticed that you have event handlers attached to the same button. In that case my initial answer would not work, because first event hander would be executed every time you click the button.
It is not very clear from the description what you want to do with your first event hander. I assume you want to use some data, and if you already have this data, then you use it immediately (like in second handler), if you don't have it - you make the AJAX call to get the data (like in first handler).
For such scenario you could use single event handler with some conditions:
var isAjaxRunning = false; // true only if AJAX call is in progress
var dataYouNeed; // stores the data that you need
$('#button-cancel').on('click', function() {
if(isAjaxRunning){
return; // if AJAX is in progress there is nothing we can do
}
// check if you already have the data, this assumes you data cannot be falsey
if(dataYouNeed){
// You already have the data
// perform the logic you had in your second event handler
}
else { // no data, you need to get it using AJAX
isAjaxRunning = true; // set the flag to prevent multiple AJAX calls
$.ajax({
url: "yoururl"
}).done(function(result) {
dataYouNeed = result;
}).always(function(){
isAjaxRunning = false;
});
}
});
You should be able to provide handlers for AJAX return codes. e.g
$.ajax({
type: "post", url: "/SomeController/SomeAction",
success: function (data, text) {
//...
},
error: function (request, status, error) {
alert(request.responseText);
}
});
you can disable the button as soon as it enters in to the event and enable it back in ajax success or error method
$('#button-cancel').on('click', function() {
// Disable button
if(ajax call is completed) {
//do some thing
//enable it back
}
});
This is edited, more complete version of dotnetums's answer, which looks like will only work once..
// introduce variable
var ajaxIsRunning = false;
$('#button').on('click', function() {
// check state of variable, if running quit.
if(ajaxIsRunning) return al("please wait, ajax is running..");
// Else mark it to true
ajaxIsRunning = true;
// in ajax complete event you change the value of variable:
$.ajax({
url: "yoururl"
}).done(function() {
// Set it back to false so the button can be used again
ajaxIsRunning = false;
});
});
You just need to set a flag that indicates ajax call is underway, then clear it when ajax call returns.
var ajaxProcessing = false;
$('#button-cancel').on('click', function(){
processAjaxCall();
});
function processAjaxCall() {
if(ajaxProcessing) return;
ajaxProcessing = true; //set the flag
$.ajax({
url: 'http://stackoverflow.com/questions/36506931/javascript-how-to-check-if-operation-has-been-completed-on-this-event'
})
.done(function(resp){
//do something
alert('success');
})
.fail(function(){
//handle error
alert('error');
})
.always(function(){
ajaxprocessing = false; //clear the flag
})
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="button-cancel">Cancel</button>
What you can do is call a function at the end of an if statement like
if(ajax call is completed) {
checkDone();
}
function checkDone() {
alert("Done");
}

form.submit fires multiple times, one extra time after each response

I have a form.submit that fires multiple times. The first time, it's fine. After I get the response back, if I click the submit button again, it fires twice. Then thrice. Seems like each time the response comes back, the submit fires an extra time the next time the button is clicked.
RetrievePassword = function () {
var $popup = $("#fancybox-outer");
var form = $popup.find("form");
form.submit(function (e) {
var data = form.serialize();
var url = form.attr('action');
$.ajax({
type: "POST",
url: url,
data: data,
dataType: "json",
success: function (response) {
if (response.Success) {
$.fancybox.close();
}
alert(response.Message);
},
error: function (xhr, status, error) {
alert(xhr.statusText);
}
});
e.cancelBubble = true;
if (e.stopPropagation) e.stopPropagation();
return false;
});
};
I'm not even sure how to debug this. Any advice is appreciated...
I assume you are calling RetrievePassword() multiple times. Everytime you call it another onsubmit handler will be registered.
The solution is to register the handler only once.

Whats the easiest way to reactive a submit() action that was cancelled with 'return false'

I have some image buttons that have jQuery event handlers attached to them.
I want to make an AJAX call in the click() event to determine if the action should actually be allowed. Because I am doing an async ajax call I have to return 'false' to immediately cancel the event and wait for the response.
$('[id^=btnShoppingCartStep_]').click(function() {
var stepName = this.id.substring("btnShoppingCartStep_".length);
$.ajax({
type: "POST",
url: $.url("isActionAllowed"),
data: "requestedStep=" + stepName,
dataType: "json",
success: function(data) {
if (data.allowed) {
// need to resume the action here
}
else {
AlertDialog(data.message, "Not allowed!");
}
}
});
return false;
});
I need to find the best way to resume the click event if the AJAX call determines that it should be allowed.
Any way of doing this that I can come up with seems clumsy, such as :
1) remove event handler from the buttons
2) simulate a click on the button that was clicked
Is there any nice way of doing this that I'm missing?
How long does it take to confirm the validity of the request? What else would be the user be doing during that time?
Why not have the server do the validation? Is that too risky? You could simply pass the data along to the server, have it determine if it's valid. If it's not, it tells Ajax "not allowed", the function alerts the user. If it liked the data, there is no need to resume the action as it's already done.
if you need submit form:
$('#form_id').submit();
if you need continue this function:
var allowed_actions = {};
$('[id^=btnShoppingCartStep_]').click(function() {
var stepName = this.id.substring("btnShoppingCartStep_".length);
var $click_me_again = $(this);
if (!allowed_actions[stepName]) {
$.ajax({
type: "POST",
url: $.url("isActionAllowed"),
data: "requestedStep=" + stepName,
dataType: "json",
success: function(data) {
if (data.allowed) {
// need to resume the action here
allowed_actions[stepName] = true;
$click_me_again.click();
}
else {
AlertDialog(data.message, "Not allowed!");
}
}
});
return false;
} // end if
// continue function (check passed)
});
Assign an ID to your form. Let's say you name it myForm. Where your // need to resume the action here is, use this:
$("#myForm").trigger("submit");
1) Simply call the form's submit() method.
$("#FormID").submit();
2) Also, if what you want is to intercept form submissions for that for, you may want to do this slightly differently (e.g. if you can submit the form via >1 button):
$("form").submit(function() {
...

Categories