Ajax is not aborting when button was clicked - javascript

How can I abort an ajax request when a button was clicked? I tried some answers I found here but it didn't work on me.
<button type="button" id="toStop">Stop</button>
When the stop button was clicked ajax isn't aborting.
function() {
var myajaxreq = $.ajax({
url: myurlhere,
type: 'GET',
async: true,
success: function(result) {
}
beforeSend: function () {
if(document.getElementById('toStop').clicked == true) {
myajaxreq.abort();
}
}
});
}

You need a separate click listener that will abort ajax request. Using beforeSend will not always work.
$('#toStop').click(function(e) {
e.preventDefault();
// abort here
// make sure myajaxreq is accessible in this function
if (myajaxreq) myajaxreq.abort();
});

Related

jQuery Click Handler with Called Ajax Sub-Method has a strange delay on $(this).prop('disabled', true) [duplicate]

This question already has answers here:
updated UI not showing before sync ajax call
(2 answers)
Closed 3 years ago.
I have a strange situation where the following Click-Handler (via one() to prevent double-clicks) has a called Ajax method from the inside. The first thing it's supposed to do is to disable my button.
Normally, if I don't have any Ajax inside and just have a simple click handler, this works and disables the button immediately:
$('#button').one('click', function (event) {
$(this).prop('disabled', true);
});
But if I have the following, with a called sub-method which involves Ajax, I notice that the 1st statement (Disable Button) does not occur until the sub-method is complete. But why? The button should get disabled immeditely as the first statement, regardless of how long the Ajax takes to complete.
$('#submitButton').one('click', function (event) {
$(this).prop('disabled', true); // Doesn't get disabled until AFTER submitSurvey()
submitSurvey(); // Call some method that does Ajax
});
function submitSurvey() {
$.ajax({
url: 'surveyProcess',
type: 'post',
processData: false,
contentType: false,
data: formData,
async: false, /* Note async = false, so nothing asynchronous here either */
success: function() {
//...
}
What could be going on here? I just need to disable the button immediately, without any delay.
You can use beforeSend() event for the same use
$('#submitButton').on('click', function (event) {
$.ajax({
url: 'surveyProcess',
type: 'post',
processData: false,
contentType: false,
data: formData,
async: false, /* Note async = false, so nothing asynchronous here either */
beforeSend: function(){
$(this).prop('disabled', true);
},
success: function() {
//...
}
});
});

onclick not triggering all codes in jquery

I'm trying to show spinner and overlay before sending an ajax request. But The onclick event directly sending the ajax request without showing the overlay and spinner. Can anyone point me out what i'm doing wrong! here is my code
$(document).ready(function() {
$(".refreshBtn").on('click', function() {
$("#overlay").css('display', 'block');
$(".spinner").css('display', 'block');
TableDataContent();
});
function TableDataContent() {
$(".all_tab_content").html('');
var tableDiv = '<div id="Leaderboard" class="tabcontent"><table class="table-striped"><tbody></tbody></table></div>';
$(".all_tab_content").append(tableDiv);
var tableBody = $('#Leaderboard tbody');
$.ajax({
type: 'get',
url: 'https://sheets.googleapis.com/v4/spreadsheets/{SHEET_ID}/values/Leaderboard?key={API_KEY}',
async: false,
success: function(response) {
}
});
$("#overlay").css('display', 'none');
$(".spinner").css('display', 'none');
}
});
You are hiding the spinner before ajax finishes put hide them from inside the complete callback so they can be hidden even when the ajax fails.
$.ajax({
type: 'get',
url: 'https://sheets.googleapis.com/v4/spreadsheets/{SHEET_ID}/values/Leaderboard?key={API_KEY}',
async: false,
success: function(response) {
},
complete: function(xhr, textStatus){
$("#overlay").css('display', 'none');
$(".spinner").css('display', 'none');
}
});
Your spinner does not show because AJAX requests are asynchronous. It means that it will be executed while the script continue to be executed too.
To correct that, move instructions which hide the overlay and the spinner in the success callback of your AJAX.
Right now you are hiding .spinner and #overlay without waiting for ajax to complete. Ajax's success callback happening when data is received, this is exactly the moment you want hiding .spinner and rest.
$.ajax({
type: 'get',
url: 'https://sheets.googleapis.com/v4/spreadsheets/{SHEET_ID}/values/Leaderboard?key={API_KEY}',
async: false,
success: function(response) {
$("#overlay").css('display', 'none');
$(".spinner").css('display', 'none');
// rest of your business
}
});
The problem is entirely due to your use of async: false. It's incredibly bad practice as it prevents the browser from being updated while the request is in progress. It's for this reason you never see the UI changes.
To fix this, remove async: false and instead work with the async callbacks of $.ajax(), like this:
$(function() {
$(".refreshBtn").on('click', function() {
TableDataContent();
});
function TableDataContent() {
var $indicators = $("#overlay, .spinner").show(); // show the loading indicator when the request starts...
var tableDiv = '<div id="Leaderboard" class="tabcontent"><table class="table-striped"><tbody></tbody></table></div>';
$(".all_tab_content").empty().append(tableDiv);
var $tableBody = $('#Leaderboard tbody');
$.ajax({
type: 'get',
url: 'https://sheets.googleapis.com/v4/spreadsheets/{SHEET_ID}/values/Leaderboard?key={API_KEY}',
success: function(response) {
// work with the response here...
},
complete: function() {
$indicators.hide(); // hide the loading indicator when the request ends
}
});
}
});
Note the use of empty(), show() and hide() here.
You also presume you need to change {SHEET_ID} and {API_KEY} in the URL to their actual values - presuming that's not just redacted data in the question.

Disable button link on beforeSend ajax

I have a button link on my view like so:
Go Somewhere
Now, I am using ajax on my page to submit values to my webApi controller methods, and when I do, I would like the button link to be disabled. Here is my ajax:
$.ajax({
url: myUrl,
method: "DELETE",
beforeSend: function () {
disableSendButton();
},
success: function() {
row.remove();
toastr.options = {
onHidden: function () {
window.location.href = redirectUrl;
},
timeOut: 2000
}
toastr.success("Success.");
}
});
function disableSendButton() {
$("#My-Btn").addClass("ui-disabled");
}
This does not work for me. The button is still active during ajax call. How do I disable this button during ajax call?
Use
$("#My-Btn").prop('disabled', true).addClass("disabled");
And add CSS
.disabled{
cursor: not-allowed;
}
This will put a disabled cursor on your button.
can you try this .attr("disabled", "disabled"); on your button

abort previous ajax call on event

the problem is that when I click on .personalized class it does not have both #loading_personalized and #divPersonalized so it takes the AJAX call ..and as soon as I click again on .personalized in time the id #loading_personalized is showing up it hides but the previous AJAX call is not cancelled yet so it executes and shows #divPersonalized, but I want that at the time the #loading_personalized is showing up and I click on .personalized the previous AJAX call should also cancel..
here is my code......
$(document).ready(function(){
$(".Personalized").click(function(){
if($("#divPersonalized").is(':visible')){
$('#triangle-personalized').hide();
$("#divPersonalized").hide();
}
else if($('#loading_personalized').is(':visible'))
{
$('#loading_personalized').hide();
//if this event is true, abort previous ajax call here
}
else {
$.ajax({
type:"POST",
url:"personalized.php",
cache:false,
beforeSend: function(){
$('#loading_personalized').show();
$('#triangle-personalized').show();
},
complete: function(){
$('#loading_personalized').hide();
},
success: function(html){
$("#divPersonalized").html(html).show();
}
});
}
});
You need to store jQuery ajax object and then call abort()
myAjaxCall = $.ajax({
type:"POST",
url:"personalized.php",
cache:false,
beforeSend: function(){
$('#loading_personalized').show();
$('#triangle-personalized').show();
},
complete: function(){
$('#loading_personalized').hide();
},
success: function(html){
$("#divPersonalized").html(html).show();
}
});
if($('#loading_personalized').is(':visible'))
{
$('#loading_personalized').hide();
myAjaxCall.abort();
}

unbind event handlers while ajax in progress

I have a text field with keypress event handler jsfiddle. And when I type something in this field and press "Enter" 2 times, 2 requests will be send. I want to turn off all events, while ajax request in progress. One option is to call .off() function before ajax call, and then bind event handler again. Any other options?
use the callback handlers from your ajax call and a boolean used as flag. By setting the ajaxLoading boolean to false in the "always" callback, you can be sure that other, future requests can be made independent from whether the current ajax call throws an error or not.
var ajaxLoading = false;
if(!ajaxloading){
ajaxloading=true;
$.ajax({
url: 'your url',
type: 'GET',
dataType: 'JSON'
})
.done(function(data) {
console.log("success");
})
.fail(function() {
console.log("error");
})
.always(function() {
console.log("complete");
ajaxloading=false;
});
}
I use 2 boolean flags, like:
var is_requesting = false, should_request = false;
function onkeydown() {
if (is_requesting) {
should_request = true;
return;
}
is_requesting = true;
$.ajax({}, function () {
is_requesting = false;
if (should_request) {
onkeydown();
}
});
}
Is there a good reason for you not to use the jQuery .off() function?
If so then you could simply disable the control prior to making the ajax request and re-enable it once the request is complete. This would also stop the user from thinking he/she could change the result by changing the text value during the request.
//Disable the input
$('#myresult').prop('disabled', true);
$('#myresult').append('<br>'+$(this).val());
$.ajax({
type: "POST",
beforeSend: function() {},
complete: function() {
//Re-Enable the input
$('#myresult').prop('disabled', false);
},
url: "/echo/json/",
data: { delay : 3 },
success: function(){},
error: function() {},
dataType: 'json'
});

Categories