ajax encapsulated request needs to wait for accumulated result [duplicate] - javascript

This question already has answers here:
jQuery Deferred - waiting for multiple AJAX requests to finish [duplicate]
(3 answers)
Closed 8 years ago.
my web app as the following structure in ajax requests:
$.ajax({
type : "GET",
url: '...',
dataType: "xml",
success: function(xml) {
$.ajax({
type : "GET",
url : "....",
dataType : "xml",
success : function(xml) {
},
error : function(xhr) {
alert(xhr.responseText);
}
});
$.ajax({
type : "GET",
url : "....",
dataType : "xml",
success : function(xml) {
},
error : function(xhr) {
alert(xhr.responseText);
}
});
$.ajax({
type : "GET",
url : "...",
dataType : "xml",
success : function(xml) {
},
error : function(xhr) {
alert(xhr.responseText);
}
});
}
});
I need all the resquests that are beeing made here to finish before i do something else. Because i need them to load content into a div. and then append that to a html element in my code.
And i dont want to use (document).ajaxStop because that will ruin my code later on.
How can i achieve this?

You can use differed($.Deferred) Objects to make your code look more clean,
Every $.ajax request returns you a differed object, and use them with $.when and .done() combination like the following
$.when(req1, req2, req3).done(function (resp1, resp2, resp3) {
//This will be executed on the success of all three requests
})
In your case you can do as follows
var req1 = $.ajax({type:"GET", url: "..."});
req1.done(function (resp1) {
// This will execute after the first request is done
var req2 = $.ajax({type:"GET", url: "..."}),
req3 = $.ajax({type:"GET", url: "..."}),
req4 = $.ajax({type:"GET", url: "..."});
$.when(req2, req3, req4).done(function (resp2, resp3, resp4) {
// when other three request are done
});
// If there are arbitrary number of requests, please consider the following
var requestsArray = [],
numberOfRequests = 10;
for (var i=0; i<numberOfRequests; i++) {
var request = $.ajax({type:"GET", url: "..."});
requestsArray.push(request);
};
$.when.apply(null, requestsArray).done(function () {
// You can collect the responses in the same order from `arguments`
var responses = arguments;
});
});
Deferred objects provide a very nice way to handle callbacks,
To know more on Deferred objects check this out http://api.jquery.com/category/deferred-object/

jQuery's $.ajax returns a promise ($.Deferred) by default. So you don't have to use callbacks and you can use these promises instead. Then using the $.when function you can create a new promise which will wait for these 3 promises to finish and the do all actions you need.
Look at the example in the bottom of the linked page to see how it works.
Edit: If the documentation is right then it should look like this:
$.ajax({
type : "GET",
url: '...',
dataType: "xml"
})
.then(function (xml) {
return $.when(
$.ajax({
type : "GET",
url : "....",
dataType : "xml"
}),
$.ajax({
type : "GET",
url : "....",
dataType : "xml"
}),
$.ajax({
type : "GET",
url : "...",
dataType : "xml"
})
);
})
.then(function (res1, res2, res3) {
var xml1 = res1[0], xml2 = res2[0], xml3 = res3[0];
});
But I didn't test it so I don't know if it's really right.

I think you can use Jquery Deffer, like that.
Serial call
$.ajax('http://echo.jsontest.com/id/1')
.then(function(result){
console.log(JSON.stringify(result));
return $.ajax('http://echo.jsontest.com/id/2')
}).then(function(result){
console.log(JSON.stringify(result));
return $.ajax('http://echo.jsontest.com/id/3')
}).then(function(result){
console.log(JSON.stringify(result));
});
Paralel call
$.when(
$.ajax('http://echo.jsontest.com/id/1'),
$.ajax('http://echo.jsontest.com/id/2'),
$.ajax('http://echo.jsontest.com/id/3')
).then(function(result1, result2, result3){
console.log(JSON.stringify(result1[0]));
console.log(JSON.stringify(result2[0]));
console.log(JSON.stringify(result3[0]));
})

Related

how to set a deferred on ajax with jquery?

let me start with some code:
function sendAjax(data, type)
{
$.ajax({
type : "GET",
dataType : "jsonp",
url : rest + type,
data : data,
});
}
$.when(sendAjax(someData, 'url')).then(function(data){
console.log(data); //undefined
});
$.when(sendAjax(someOtherData, 'url')).then(function(data){
console.log(data); //undefined
});
the issue i'm having is that data comes in as undefined
if i use success in the $.ajax the data comes in fine
The main idea here is that i should write the sendAjax() method once and use it through the application, but i don't think i set it up properly
ant ideas?
You need to return the promise return by $.ajax() from sendAjax
function sendAjax(data, type)
{
return $.ajax({
type : "GET",
dataType : "jsonp",
url : rest + type,
data : data,
});
}

JQuery ajax() done / fail callbacks not returning upon status 200

I'm trying to post a form data using JQuery to a remote servlet.
I can see that the server receives the data and also returns status code 200 and a response string of "{result: 'success'}"
But the ajax call doesn't return with the done or fail functions (if I add an always function than I can see that it is being called)
Here's a code snippet of the client side:
`
var dataParams = 'email='+email+'&password='+password;
var url = 'http://127.0.0.1:8888/signup';
var jxhr = $.ajax({
type : "POST",
url : url,
data : dataParams,// serializes the form's elements.
dataType: "json",
done: function() {
console.log("done!");
hideSignUp();
showThankYou(); },
fail: function() {
console.log("fail!");
}
});
`
Seems like I'm missing out on something, but can't seem to find what.
Note that I'm using JQuery 1.8.3 so success is deprecated.
Any thoughts?
Try:
var url = "http://127.0.0.1:8888/signup";
var jxhr = $.ajax({
type : "POST",
url : url,
data : dataParams,// serializes the form's elements.
dataType: "json"
}).done(function() {
console.log("done!");
hideSignUp();
showThankYou();
}).fail(function(jqXHR, textStatus) {
console.log(textStatus);
});
Try chaining your callbacks, rather than setting them as object fields:
$.ajax({
type : "POST",
url : url,
data : dataParams,// serializes the form's elements.
dataType: "json"
}).done(function (xhrResponse) {
console.log("done!");
hideSignUp();
showThankYou();
}).fail(function (xhrResponse, textStatus) {
console.log(textStatus);
}).always( function () {
console.log("I'm done with this.");
});
By chaining your callbacks, you guarantee execution of at least one (complete).

Load json file dynamically - javascript

please check this:
var scripts = {};
require = function(src){
var id = Math.round(+new Date()/1000);
$.ajax({
url: src + '.json',
type: 'GET',
dataType: "json",
cache: false,
async: false,
success : function(data){
scripts[id] = data;
}
});
return scripts[id];
}
return undefined :/ What is the problem!? i don't know...
EDIT! 'async : false' and run!
It is because $.ajax is asynchronous in your call.
return scripts[id];
The above line is executed even before the success callback is triggered.
it is a asynchronous call. scripts is empty when you return.
to verify the cause,
window.scripts = {};
require = function(src){
var id = Math.round(+new Date()/1000);
$.ajax({
url: src + '.json',
type: 'GET',
dataType: "json",
cache: false,
success : function(data){
window.scripts[id] = data;
alert(window.scripts)
}
});
//return scripts[id];
}
after alert, see the value of window.scripts
its async issue .. Ajax call is called asynchrnously.
return scripts[id];
is executed before ajax call return.s
Your problem is that the call is asynchronous. This means that your method is returning before the call is finished.
Instead of returning the scripts[id] try this instead:
require = function(src){
var id = Math.round(+new Date()/1000);
$.ajax({
url: src + '.json',
type: 'GET',
dataType: "json",
cache: false,
success : function(data){
scripts[id] = data;
DoStuff(scripts[id]);
}
});
}
DoStuff(data) {
// do whatever it is you were going to do after the return.
}

Jquery ajax request not able to return data to other function

I am making a simple ajax request using jquery . Below is my ajax function .
var makeJqueryAjaxRequest = function(arrParam) {
var request = $.ajax({
url : arrParam['url'],
async: false,
type: arrParam['type'],
data: arrParam['data'],
dataType: arrParam['data_type'],
success: function(data) {
if(data){
return data;
}
}
});
}
here is my function calls :
var items = {
"type" : 'POST',
"url" : ajaxGetUrl,
"data" : arrParam['data'],
"data_type" : 'html'
};
var msg = makeJqueryAjaxRequest(items);
Now don't know why my makeJqueryAjaxRequest function always returns the null value. If I alert the data in the success : I'm getting the data perfect . But when I try to return it gives me the null value
You can't return value from an Asynchronous callback function.
Because success is a async callback which is called by jQuery when a ajax Event(success in this case) fires. So returning something from this functions will not have any effect as they will be returned to jQuery code.
You can use the following
var makeJqueryAjaxRequest = function(arrParam) {
var request = $.ajax({
url : arrParam['url'],
async: false,
type: arrParam['type'],
data: arrParam['data'],
dataType: arrParam['data_type']
});
return request;
}
Then do
makeJqueryAjaxRequest(items).done(function(data){
if(data){
var msg = data;
// do whatever you like with msg now
}
});
Alternative Callback Approach:
var makeJqueryAjaxRequest = function(arrParam,callback) {
var request = $.ajax({
url : arrParam['url'],
async: false,
type: arrParam['type'],
data: arrParam['data'],
dataType: arrParam['data_type'],
success: function(data) {
if(data){
callback(data);
}
}
});
}
Then use it like
makeJqueryAjaxRequest(items,function(data){
// do whatever you like with data
});
Doc on $.ajax()
Note
And with either of these approach async: false is not necessary. You can remove that. As the doc says
As of jQuery 1.8, the use of async: false is deprecated

Jquery: how to send one ajax request and save the JSON string for another calls

in my code i have the following
var response = "";
function send_ajax(){
if(response == ""){
$.ajax({
url: url
type: 'POST',
dataType: "JSON",
success: function(data){
response = data;
}
});
}
}
my problem is that send_ajax function is called several times in my script, and sometimes alot of ajax calls is send together and no need for that. so i'm searching for a solution in which if one ajax request is send other calls should wait until that function saves the data in the response var and use it.
how can i do that ?
If you set the async flag to false, no other calls are made until the first call is done.
$.ajax({
url: url
type: 'POST',
dataType: "JSON",
async: false,
success: function(data){
response = data;
}
});
if(response == ""){
response = 'waiting';
will do the trick, no ?
Another solution if you want the $.ajax to be async, but only allow one ajax request at any time. You could take a look at $.ajaxStart and $.ajaxStop global event
var ajaxLock = false;
$.ajaxStart(function(){ajaxLock = true;});
$.ajaxStop(function(){ajaxLock = false;});
var ajaxRequest = function(url, data) {
if (!ajaxLock) {
$.ajax({
url: url
type: 'POST',
dataType: "JSON",
async: false,
success: function(data){
response = data;
}
});
}
}

Categories

Resources