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();
}
Related
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();
});
The first time a submit form the success message displays and then fades correctly. If I submit form again then it doesn't work. I want it to repeat the display of message and subsequent fade out after each form submit.
I found this answer
Trying to have a JQuery flash message after an ajax from submit in show again after more than one form submit (in rails)
but couldn't get to work, I'm very new to all this so be gentle ;-)
$(document).ready(function() {
$("#editMember").submit(function(e) {
e.preventDefault();
$.ajax( {
url: "php/adminUpdateMember.php",
method: "post",
data: $("form").serialize(),
dataType: "text",
success: function(strMessage) {
$("#message").text(strMessage);
}
});
});
setTimeout(function() {
$('#message').fadeOut('fast');
}, 4000);
});
Your setTimeout() call is not inside your submit() block. It will trigger the fadeOut 4 seonds after page load, and not be called again.
You might also need to call $('#message').show(), to make the element visible after it's been faded out.
$(document).ready(function() {
$("#editMember").submit(function(e) {
e.preventDefault();
$.ajax( {
url: "php/adminUpdateMember.php",
method: "post",
data: $("form").serialize(),
dataType: "text",
success: function(strMessage) {
$("#message").text(strMessage);
$('#message').fadeIn('fast');
}
});
setTimeout(function() {
$('#message').fadeOut('fast');
}, 4000);
});
});
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.
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'
});
I want to show a div with a loading animation over my page while the page loads some XML content. Once its loaded, I want to hide this div. How can I go about doing this?
$.ajax({
url: '/test.xml',
beforeSend: function(XMLHttpRequest) {
// Show the div before sending the request
$('#load').show();
},
complete: function(XMLHttpRequest, textStatus) {
// Hide the div no matter if the call succeeded or not
$('#load').hide();
},
success: function(xml) {
// if the request succeeds do something with the received XML
}
});
$.ajax({
type: "GET",
url: "your.xml",
dataType: "xml",
beforeSend: function() {
$('#div').fadeIn();
},
success: function(xml) {
// example for parsing xml
$(xml).find('YOUR_XML_TAG').each(function(){
// append xml to page HERE
});
},
complete: function() {
$('#div').fadeOut();
}
});
#cballou Your code will leave '#div' "up", if $.ajax() has not suceeded for any of numerous possible reasons.
Almost right ;)
Never under-estimate the importance of removing redundant $() calls. So ...
//all of this is inside some closure or function
var $blanket = $("#div") ;
// check if after last call, something has possibly removed your '#div'
// throw if false
ASSERT( $blanket.length === 1 ) ;
$.ajax({
type: "GET",
url: "your.xml",
dataType: "xml",
beforeSend: function() { $blanket.fadeIn();
},
success: function(xml) {
// example for parsing xml
$(xml).find('YOUR_XML_TAG').each(function(){
// append xml to page HERE
});
},
complete: function() { $blanket.fadeOut();
}
});
--DBJ
I would use the onbeforeunload event fired when the page URL changes, to create an overlay div with opacity at 0.5, which will be replaced by the new content when the page is loaded.