Trigger success handler is finished executing, with nested ajax requests - javascript

I have many nested ajax requests like below. I have a lot of things going on in the success function below, I need something like success that will trigger when success is complete. complete(jqXHR, textStatus) just seems to fire with success and I don't think .ajaxComplete() works.
$.ajax({
url: 'api/periods.json',
dataType: 'json',
success: function (d1) {
//more nested ajax requests
},
});
SOLUTION:
A $.ajax() replacement plugin called $.fajax() (finished + ajax) has been created. Please check it out and let me know what you think. https://github.com/reggi/fajax (It's pretty well documented).

You could create a wrapper function for jQuery.ajax to make this a little cleaner:
var started = 0, done = 0;
var globalHandler = function(){
//do stuff when all success handlers are done
}
function handleAjax(args){
var _success = args.success || function(){};
args.success = function(jqXHR, textStatus){
_success(jqXHR, textStatus);
done++;
if(done >= started)
globalHandler();
}
var ajax = $.ajax(args);
started++;
return ajax;
}
usage
handleAjax({
url: 'api/periods.json',
dataType: 'json',
success: function (d1) {
//more nested ajax requests like this:
handleAjax({...});
}
});
This creates a closure so don't do any crazy memory-intensive stuff in there and you should be fine.

I'm not quite totally sure of what you're asking, so forgive me if I'm off-kilter, but I think you might want something like:
$.ajax({
url: 'api/periods.json',
dataType: 'json',
success: function(d1){
//more nested ajax requests
},
}).done(function(msg){
alert("Every Ajax Call is Complete!");
});

You may want .queue() or .Defered
$("#el").queue("queue_name",function(){
$.ajax({
url: 'api/periods.json',
dataType: 'json',
success: function(d1){
//more nested ajax requests
$("#el").dequeue("queue_name"); // tell queue success is complete
},
});
}).queue("queue_name",function(){
//do something you want when success is complete
})
$("#el").dequeue("queue_name"); // start to execute
or $.Deferred()
$.ajax({
url: 'api/periods.json',
dataType: 'json',
success: function(d1){
var start = function(){
var dtd = $.Deferred();
//more nested ajax requests---------------
$.post("xxx",function(){
dtd.resolve(); // when success is complete
});
//----------------------------------------
return dtd.promise();
}
start.apply(this).pipe(function(){
//do something you want when success is complete
});
},
});

Related

Design to block asynchronous javascript

var flow;
$.ajax({
url: "qa/version.json",
dataType: "json",
success: function( response ){
flow = response.Version;
}
});
$(".flow").append(flow);
Due to the nature of JS asynchronous design, the append would will be execute before it is being assigned a value in ajax call. What is the best way to tell the script to wait until flow gets assigned in ajax call, then do the append? I do not want to put append right below the success, I would like to keep them separate.
The "best way" is to perform the action in response to the asynchronous action:
$.ajax({
url: "qa/version.json",
dataType: "json",
success: function(response){
$(".flow").append(response.Version);
}
});
If you want to "keep them separate" then you can define a function to call in the response:
var appendFlow = function (flow) {
$(".flow").append(flow);
};
$.ajax({
url: "qa/version.json",
dataType: "json",
success: function(response){
appendFlow(response.Version);
}
});
Separating the code into its own function is simply a matter of organizing your code into re-usable components. Either way, by design the response can't be processed until it's received, so you'd perform your actions in response to the asynchronous call.
Anything wrong with:
$.ajax({
url: "qa/version.json",
dataType: "json",
success: function( response ){
flow = response.Version;
$(".flow").append(flow);
}
});
I have no idea why you don't want to put your success handler in the spot for a success handler, but here's an alternative that may help you.
jQuery returns a Deferred instance when you make AJAX requests. You can use its .done() method to set up a callback later.
var dfd = $.ajax( /* your code here, without the success handler */);
// later on...
dfd.done(function (response) {
$('.flow').append(response.Version);
});
See also:
https://api.jquery.com/deferred.done/
https://api.jquery.com/jquery.deferred/
Or:
var request = $.ajax({
url: "qa/version.json",
dataType: "json"
});
request.done(function(response){
$(".flow").append(response.Version);
});

Recursive ajax() requests

I use jQuery's ajax()to get information. I call the method when the request is successful. Here is the code:
function recursively_ajax(){
console.warn("begin");
$.ajax({
type:"GET",
url: "./JvmInfoClass",
success: function(data){
console.warn("get jvm info success");
recursively_ajax();
}
});
}
recursively_ajax();
I make the thread sleep 3 seconds in the back-end. But the console print the message continuously not after 3 seconds. Why is this?
You can try this with ajax call async:false
var counter=0;
function recursively_ajax()
{
var pass_data=5;
var chartMenu=['VTR','NC','RC','TOCU','TOCO','TR','COA','MP'];
$.ajax({
type:"POST",
async:false, // set async false to wait for previous response
url: "url to server",
dataType:"json",
data:{dataMenu:pass_data},
success: function(data)
{
counter++;
if(counter < chartMenu.length){
recursively_ajax();
}
}
});
}
recursively_ajax();
in that case the bug is in the server side code because the server should sent back the response only after 3 seconds.
But I would recommend to use setTimeout() in the client side to restrict the request frequency
Try
function recursively_ajax(){
console.warn("begin");
$.ajax({
type:"GET",
url: "./JvmInfoClass",
success: function(data){
console.warn("get jvm info success");
setTimeout(recursively_ajax, 3000)
}
});
}
recursively_ajax();
It's browser's cacheing problem,I append the date to the url or set the ajax cache:false,the problem is solved.Thank everyone.

javascript variable equal to value from function [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How to return AJAX response Text?
How to return the response from an AJAX call from a function?
So I have a javascript function where I'm doing an AJAX call to see if the user is online or offline. It looks something like this.
function onlineStatus(){
$.ajax({
url: "assets/ajax/online-offline.php",
cache: false,
success: function(html){
return html;
}
});
}
I would like to assign the value from this function as a variable that I can then use.
Something like this.
var test = onlineStatus();
if (test == "true")
alert("online");
else
alert("offline");
Is this possible? I must be doing something wrong, but can't figure out how to achieve this result. Thanks
// Edit:
Thanks for your help everyone, sorry, didn't realize it may have been a duplicate question. I wasn't sure what to search for initially, so I didn't see anything related.
$.ajax is asynchronous so you can't return anything from onlineStatus, you need to pass it a callback function that can be called when the ajax call completes.
function onlineStatus(callback){
$.ajax({
url: "assets/ajax/online-offline.php",
cache: false,
success: callback
});
}
onlineStatus(function(test) {
if (test == "true")
alert("online");
else
alert("offline");
});
Since calls happen asynchronously, you'll have to pass a callback function into onlineStatus. Something like:
function onlineStatus(callback){
$.ajax({
url: "assets/ajax/online-offline.php",
cache: false,
success: function(html){
callback(html);
}
});
}
And then call it with:
onlineStatus(function (html)
{
// Do stuff with the status
});
You can simple use a deferred object.
function onlineStatus(){
var request = $.ajax({
url: "assets/ajax/online-offline.php",
cache: false
});
return request;
}
var test = onlineStatus();
test.done(function(html) {
if (html)
alert("online");
else
alert("offline");
});
$.ajax returns a jqXHR, so you can use .done:
jqXHR.done(function(data, textStatus, jqXHR) {});
An alternative construct to the success callback option, the .done() method replaces the deprecated
AJAX is asynchronous, that's what the A stands for. You need pass a callback.
For example:
function onlineStatus(callback){
$.ajax({
url: "assets/ajax/online-offline.php",
cache: false,
success: callback
});
}
onlineStatus(function(data) {
if (data == "true") {
alert "online";
}
else {
alert "offline";
}
}
The $.ajax method is asynchronous so you need to handle its return values in the callback.
function onlineStatus(){
$.ajax({
url: "assets/ajax/online-offline.php",
cache: false,
success: function(html){
if (html == "true")
alert("online");
else
alert("offline");
}
});
}
you can do like this.......but it is not a good method because synchronous request by ajax makes your code slow.......
function onlineStatus(){
var data;
$.ajax({
url: "assets/ajax/online-offline.php",
cache: false,
async:false,
success: function(html){
data = html;
}
});
return data;
}
or
if you only want to dispaly the alert box then...
function onlineStatus(){
$.ajax({
url: "assets/ajax/online-offline.php",
cache: false,
success: function(html){
if (html== "true")
alert("online");
else
alert("offline");
}
});
return data;
}
jQuery ajax call is an asynchronous call. You will have to wait to get the results before you can use them for showing the alert.
var isOnline = false;
checkOnlineStatus();
function checkOnlineStatus(){
$.ajax({
url: "assets/ajax/online-offline.php",
cache: false,
success: callback
}
});
}
function callback(html){
isOnline = (html == "online");
showAlert();
}
function showAlert(){
if (isOnline == "true")
alert("online");
else
alert("offline");
}

How to call second jQuery.ajax instance on success of first and update page

I have some jQuery that is triggered on click of a link with the class 'changetag'. I'm using $.ajax() to update the database via changetag.php.
I then change the visual appearance of the link by toggling the class between on/off. The code is as follows:
$(function() {
$(".changetag").click(function(){
var element = $(this);
var I = element.attr("id");
var info = 'switch_tag=' + I;
$.ajax({
type: "POST",
url: "_js/changetag.php",
data: info,
success: function(){}
});
$("#li_"+I).toggleClass("off on");
element.toggleClass("off on");
return false;
});
});
Works perfectly. But now I want to add in a second PHP call which will pull data and update another area of the page if the above was successful.
What I'm trying to add is:
$.ajax({
url: "_js/loaddata.php",
success: function(results){
$('#listresults').empty();
$('#listresults').append(results);
}
});
But just adding it into success: function(){} doesn't seem to be working. To clarify, here is the complete code I'm testing:
$(function() {
$.ajaxSetup ({cache: false});
$(".changetag").click(function(){
var element = $(this);
var I = element.attr("id");
var info = 'switch_tag=' + I;
$.ajax({
type: "POST",
url: "_js/changetag.php",
data: info,
success: function(){
$.ajax({
url: "_js/loaddata.php",
success: function(results){
$('#listresults').empty();
$('#listresults').append(results);
}
});
}
});
$("#li_"+I).toggleClass("off on");
element.toggleClass("off on");
return false;
});
});
The PHP scripts are both called successfully and the toggle class works, but the data pulled is not written to #listresults for some reason.
Ajax calls are (by default) asynchronous. That means that this code:
$("#li_"+I).toggleClass("off on");
element.toggleClass("off on");
return false;
could be executed before the ajax call preceding it is finished. This is a common problem for programmers who are new to ajax and asynchronous code execution. Anything you want to be executed after the ajax call is done must be put into a callback, such as your success handler:
$.ajax({
type: "POST",
url: "_js/changetag.php",
data: info,
success: function(){
$("#li_"+I).toggleClass("off on");
element.toggleClass("off on");
}
});
Likewise, you could put the second ajax call in there as well:
$.ajax({
type: "POST",
url: "_js/changetag.php",
data: info,
success: function(){
$("#li_"+I).toggleClass("off on");
element.toggleClass("off on");
$.ajax({
url: "_js/loaddeals_v2.php",
success: function(results){
$('#listresults').empty();
$('#listresults').append(results);
}
});
}
});
With jQuery 1.5's Deferred Object, you can make this slicker.
function firstAjax() {
return $.ajax({
type: "POST",
url: "_js/changetag.php",
data: info,
success: function(){
$("#li_"+I).toggleClass("off on");
element.toggleClass("off on");
}
});
}
// you can simplify this second call and just use $.get()
function secondAjax() {
return $.get("_js/loaddata.php", function(results){
$('#listresults').html(results);
});
}
// do the actual ajax calls
firstAjax().success(secondAjax);
This is nice because it lets you un-nest callbacks - you can write code that executes asynchronously, but is written like synchronously-executed code.
Deprecation Notice: The jqXHR.success(), jqXHR.error(), and jqXHR.complete() callbacks are removed as of jQuery 3.0. You can use jqXHR.done(), jqXHR.fail(), and jqXHR.always() instead.
https://api.jquery.com/jQuery.ajax/#jqXHR

How do I reload the page after all ajax calls complete?

The first time a user is visiting my website, I am pulling a lot of information from various sources using a couple of ajax calls. How do I reload the page once the ajax calls are done?
if(userVisit != 1) {
// First time visitor
populateData();
}
function populateData() {
$.ajax({
url: "server.php",
data: "action=prepare&myid=" + id,
dataType: "json",
success: function(json) {
if(json.error) {
return;
}
_id = response[json].id;
getInformation(_id);
}
});
}
function getInformation(id) {
$.ajax({
url: "REMOTESERVICE",
data: "action=get&id=" + id,
dataType: "json",
success: function(json) {
if(json.error) {
return;
}
$.ajax({
url: "server.php",
data: "action=update&myid=" + id + '&data=' + json.data.toString(),
dataType: "json",
success: function(json) {
if(json.error) {
return;
}
}
});
}
});
}
So what the code does is, it gets a list of predefined identifiers for a new user (populateData function) and uses them to get more information from a thirdparty service (getInformation function). This getInformation function queries a third party server and once the server returns some data, it sends that data to my server through another ajax call. Now what I need is a way to figure out when all the ajax calls have been completed so that I can reload the page. Any suggestions?
In your getInformation() call you can call location.reload() in your success callback, like this:
success: function(json) {
if(!json.error) location.reload(true);
}
To wait until any further ajax calls complete, you can use the ajaxStop event, like this:
success: function(json) {
if(json.error) return;
//fire off other ajax calls
$(document).ajaxStop(function() { location.reload(true); });
}
.ajaxStop() works fine to me, page is reloaded after all ajax calls.
You can use as the following example :
$( document ).ajaxStop(function() {
window.location = window.location;
});
How it's works?
A: Whenever an Ajax request completes, jQuery checks whether there are any other outstanding Ajax requests. If none remain, jQuery triggers the ajaxStop event.
Hope help y'all, furthermore information, I'm sharing the link of the documentation following.
source: https://api.jquery.com/ajaxstop/
You could just redirect to the same page in the server.php file where the function is defined using a header('Location: html-page');
//document.location.reload(true);
window.location = window.location;
See more at: http://www.dotnetfunda.com/forums/show/17887/issue-in-ie-11-when-i-try-to-refresh-my-parent-page-from-the-popupwind#sthash.gZEB8QV0.dpuf

Categories

Resources