Can't get ajaxStop() / ajaxComplete() to work - javascript

I have the following JS function:
function getInfo(s,n) {
$.ajax({
type : 'POST',
url : 'includes/stock_summary.php',
timeout : 10000,
data : {
s : s
}
})
.done(function(data) {
function IsJsonString(str) {
try {
JSON.parse(str);
} catch (e) {
alert("Unable to communicate with Yahoo! Finance servers. Please try again later.");
}
return true;
}
$.ajax({
type : 'post',
url : "includes/stock_desc.php",
data : {
s : s
}
})
.done(function(desc) {
$('#desc').html(desc);
})
if(data.change.charAt(0) == '+') {
$('#change').css('color','#090');
$('#puPrc').html('<img src="images/pu_prc_up.png"> ');
}
if(data.change.charAt(0) == '-') {
$('#change').css('color','#D90000');
$('#puPrc').html('<img src="images/pu_prc_dwn.png"> ');
}
var ask = data.ask+" <small>x "+data.askSize+"</small>";
var bid = data.bid+" <small>x "+data.bidSize+"</small>";
var change = data.change+" ("+data.changePc+")";
$('#ask').html(ask);
$('#lt').html(data.lastTrade);
$('#ytd').html(data.ytdReturn);
$('#bid').html(bid);
$('#dayHigh').html(data.dayHigh);
$('#dayLow').html(data.dayLow);
$('#prevClose').html(data.prevClose);
$('#vol').html(data.vol);
$('#yearHigh').html(data.yearHigh);
$('#yearLow').html(data.yearLow);
$('#change').html(change);
$('#stockName').html(n);
$('#sym').html(s.toUpperCase());
$('#open').html(data.sOpen);
})
.fail(function(e) {
alert("Unable to communicate with Yahoo! Finance servers. Please try again later.");
})
$('#chart').html("<img src='http://chart.finance.yahoo.com/z?s="+s+"&t=3m&q=l&l=on&z=m'>");
$('.popUp').bPopup();
}
It is called using onClick().
The function itself does the job correctly but I only want to trigger the line:
$('.popUp').bPopup();
when everything else has finished.
I have used $.ajaxStop(), $(document).ajaxStop(), $.ajaxComplete() and $(document).ajaxComplete()
I have tried them inside, outside, above and below the function but cannot seem to get it to do what I need it to!
The only time it has worked is outside the function but it then runs on page load, which I obviously don't want to happen. I only want it to run when the function completes.
If someone could help me out with this pickle, please help!

If you have just one ajax call you want to add a .always handler that will execute when all the .done and .fail handlers have completed.
.always(function() {
$('.popUp').bPopup();
});
If you have more than one ajax call on your page and you want the code to be fired once all the calls are completed then use the ajaxStop event.
$(function() {
$(document).on('ajaxStop', function() {
$('.popUp').bPopup();
});
});

Related

javascript update modal form element whilst the ui is blocked due to code execution

ok, I have seen many, many articles about this. But so far I have not got any to work. So this is my take on the issue.
I have a list of employee names with ids held in a select option, and a button that when clicked, calls a routine for each option in the select
$(document).on("click", ".js-button-update-all-drivers", function (e) {
e.preventDefault();
myApplication.busy(true);
$("#modalInfo-body span").text("Starting update ...........");
$('.modalInfo-header .title').text("Information");
var modal = document.getElementById('modalInfo');
myApplication.openModal(modal);
var selected = document.getElementsByClassName('js-dropdown-selector');
for (var i = 0; i < selected[0].options.length; i++) {
var Id = selected[0].options[i].value;
$("#modalInfo-body span").text("Updating - " + Id);
doWork(Id);
}
myApplication.closeModal(modal);
myApplication.busy(false);
});
This calls a function call doWork which is defined as async/wait
async function doWork(employeeId, taxWeek, taxYear) {
try {
const response = await processUpdate(Id);
} catch (err) {
$("#modalInfo-body span").text("Report Error - Thank you.");
}
}
Which in turn calls the following function:
function processUpdate(Id) {
return new Promise((resolve, reject) => {
$.ajax({
url: '/myTest',
async: false,
data: {
Id: Id
},
method: 'post',
dataType: 'json',
success: function(retData) {
if (retData === false) {
resolve('Completed');
} else {
reject('An error has occurred, please send a screen shot');
}
},
error: function(xhr, error) {
reject('An error has occurred, please send a screen shot'); }
});
});
}
Although this code works, the element $("#modalInfo-body span") is not updated as it loops around the doWork function.
I already have a spinner on the screen, but am looking for a more visual aid to how this is progressing.
OK, I am going to start this by saying that I knew the browser is single threaded, and this was not going to be easy.
I did try callbacks and that did not work completely, as I encountered a delay in updating the screen.
So ultimately, I replaced this with a simple spinner.
Thanks to all that took the timer to look at this.

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);
}

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");
}

Creating ajax request loop within an 'each' function

This topic is covered in a few other questions, but I had some difficulty applying the suggested approaches into this use case. I have a checkbox list, where a user can select n sub-sites to publish their post to. since this list could grow to be 100+, I need an efficient way to perform an expensive task on each one. It's okay if it takes awhile, as long as Im providing visual feedback, so I planned to apply an "in progress" style to each checkbox item as its working, then move to the next item int he list once it is successfully published. Also note: I'm working in the WordPress wp_ajax_ hook but the PHP side of things is working well, this is focused on the JS solution.
This code is working right now (console.logs left in for debug), but I've seen multiple warnings against using async: true. How can I achieve a waterfall AJAX loop in a more efficient way?
//Starts when user clicks a button
$("a#as_network_syndicate").click( function(e) {
e.preventDefault(); //stop the button from loading the page
//Get the checklist values that are checked (option value = site_id)
$('.as-network-list').first().find('input[type="checkbox"]').each(function(){
if($(this).is(':checked')){
blog_id = $(this).val();
console.log(blog_id+' started');
$(this).parent().addClass('synd-in-progress'); //add visual feedback of 'in-progress'
var process = as_process_syndication_to_blog(blog_id);
console.log('finished'+blog_id);
$(this).parent().removeClass('synd-in-progress');
}
});
});
function as_process_syndication_to_blog(blog_id){
var data = {
"post_id": $('#as-syndicate_data-attr').attr("data-post_id"), //these values are stored in hidden html elements
"nonce": $('#as-syndicate_data-attr').attr("data-nonce"),
"blog_id": blog_id
};
var result = as_syndicate_to_blog(data);
console.log('end 2nd func');
return true;
}
function as_syndicate_to_blog(data){
$.ajax({
type : "post",
dataType : "json",
async: false,
url : ASpub.ajaxurl, //reference localized script to trigger wp_ajax PHP function
data : {action: "as_syndicate_post", post_id : data.post_id, nonce: data.nonce, blog_id: data.blog_id},
success: function(response) {
if(response.type == "success") {
console.log(response);
return response;
} else {
}
},
error: {
}
});
}
Indeed, doing synchronous AJAX request is bad because it will block the browser during the whole AJAX call. This means that the user cannot interact with your page during this time. In your case, if you're doing like 30 AJAX calls which take say 0.5 seconds, the browser will be blocked during 15 whole seconds, that's a lot.
In any case, you could do something following this pattern:
// some huge list
var allOptions = [];
function doIntensiveWork (option, callback) {
// do what ever you want
// then call 'callback' when work is done
callback();
}
function processNextOption () {
if (allOptions.length === 0)
{
// list is empty, so you're done
return;
}
// get the next item
var option = allOptions.shift();
// process this item, and call "processNextOption" when done
doIntensiveWork(option, processNextOption);
// if "doIntensiveWork" is asynchronous (using AJAX for example)
// the code above might be OK.
// but if "doIntensiveWork" is synchronous,
// you should let the browser breath a bit, like this:
doIntensiveWork(option, function () {
setTimeout(processNextOption, 0);
});
}
processNextOption();
Notice: as said by Karl-André Gagnon, you should avoid doing many AJAX requests using this technique. Try combining them if you can, it will be better and faster.
If you can't pass the whole block to the server to be processed in bulk, you could use a jQuery queue. This is using your sample code as a base:
var $container = $('.as-network-list').first();
$container.find('input[type="checkbox"]:checked').each(function(){
var $input = $(this);
$container.queue('publish', function(next) {
var blog_id = $input.val(),
$parent = $input.parent();
console.log(blog_id+' started');
$parent.addClass('synd-in-progress'); //add visual feedback of 'in-progress'
as_process_syndication_to_blog(blog_id).done(function(response) {
console.log(response);
console.log('finished'+blog_id);
$parent.removeClass('synd-in-progress');
next();
});
});
});
$container.dequeue('publish');
function as_process_syndication_to_blog(blog_id){
var data = {
"post_id": $('#as-syndicate_data-attr').attr("data-post_id"), //these values are stored in hidden html elements
"nonce": $('#as-syndicate_data-attr').attr("data-nonce"),
"blog_id": blog_id
};
return as_syndicate_to_blog(data).done(function(){ console.log('end 2nd func'); });
}
function as_syndicate_to_blog(data){
return $.ajax({
type : "post",
dataType : "json",
url : ASpub.ajaxurl, //reference localized script to trigger wp_ajax PHP function
data : {action: "as_syndicate_post", post_id : data.post_id, nonce: data.nonce, blog_id: data.blog_id}
});
}
I don't have a test environment for this so you may need to tweak it for your use case.

$.mobile.changePage doesn't load the CSS

This is a very weird situation with ajax. I have a login page which calls the mainpage via ajax, like this:
// Function to call WCF Service - Infrastructure
function CallService() {
$.ajax({
type: Type, //GET or POST or PUT or DELETE verb
url: Url, // Location of the service
data: Data, //Data sent to server
contentType: ContentType, // content type sent to server
dataType: DataType, //Expected data format from server
processdata: ProcessData, //True or False
success: function (msg) {//On Successfull service call
ServiceSucceeded(msg);
},
error: ServiceFailed// When Service call fails
});
}
function ServiceSucceeded(result) {
if (DataType == "json") {
var resultText = result;
if (resultText.result == "True") {
$.mobile.changePage("MainMenu.aspx",{ transition: "slideup" });
}
else {
//Show Error Message
}
}
}
In every page I have a reference to an js called "general.js" which contains the following code:
function processMenu(menuOptions) {
var options = menuOptions.split('');
var currentOptions = '1234567'.split('')
for (i = 0; i < currentOptions.length; i++) {
var index = (i + 1) + '';
if (options.indexOf(index) < 0) {
var op = $('#op' + currentOptions[i]);
op.attr('disabled', true);
op.addClass('btndisabled');
$(op).live("click", function (event) {
//do stuff
event.preventDefault(); // Prevent default link behaviour
});
}
}
}
This code verifies some numbered controls and enable a CSS called "btndisabled" if it's requiered
The "btndisabled" CSS is:
.btndisabled{
background-color: rgb(236,233,216);
color: #CCC;
font-style: normal;
}
Ok the situation is, when I use
$.mobile.changePage("MainMenu.aspx?",{ transition: "slideup" });
The Login.aspx content changes to the MainMenu.aspx content and the js:
op.attr('disabled', true);
op.addClass('btndisabled');
$(op).live("click", function (event) {
//do stuff
event.preventDefault(); // Prevent default link behaviour
});
is executed, the CSS is not applied BUT the "event.preventDefault" is executed. I need to apply the CSS but I don't what is wrong. Any ideas?
UPDATE
Watching the behaviour of the object on postback and in ajax call I realized something quite intersting, but I don't know what to think about it.
On Postback
Look at the HTMLAnchorElement
Ajax
If the DOM has not loaded the anchor object, HOW IS POSSIBLE TO ASSIGN THE event.preventDefault()???
This is crazy...
Your answer is probably on the jQuery Mobile forum itself:
http://forum.jquery.com/topic/mobile-css-gets-lost-after-using-ajax-to-update-content

Categories