I have a problem passing data from a JQuery ajax call back to the calling location. The code in question is below:
jQuery("#button").click(function()
{
for(var i = 0;i < data.length; i++)
{
result = updateUser(data[i]); //result is not populated..
alert(result); //prints 'undefined'
}
});
function updateUser(user_id)
{
jQuery.ajax({
url:"/users/update/"+user_id,
type:"GET",
async: false,
success: (function(data){
//if I alert "data" here it shows up correctly
//but if i try to return it like below
//it does not get passed correctly
return data;
})
});
Any pointers are greatly appreciated
You cannot return value from an AJAX success handler like that. AJAX is asynchronous so execution will proceed to the next line where result is undefined. The only way you can get data back from an asynchronous operation is to use a callback. A callback is a function that gets called when the asynchronous operation finishes what it is doing:
jQuery("#button").click(function () {
for (var i = 0; i < data.length; i++) {
updateUser(data[i], function(result) {
alert(result);
});
}
});
function updateUser(user_id, callback) {
jQuery.ajax({
url: "/users/update/" + user_id,
type: "GET",
success: callback
});
}
Here, you're calling the callback in the success handler of the AJAX call and so now you have access to the data that was returned by the AJAX call.
Have your function return the result of calling jQuery.ajax() - this object implements the jQuery deferred promise interface. That is, an object that promises to return a result some time later.
function updateUser(user_id) {
return jQuery.ajax({...});
}
and then use .done() to register the function to be called when the promise gets resolved:
updateUser(data[i]).done(function(result) {
alert(result);
});
The important part is that deferred objects allow you to complete decouple the initiation of the asynchronous task (i.e. your updateUser function) with what's supposed to happen when that task completes (or fails).
Hence there's no need to pass any callback functions to .ajax, and you can also chain your call with other deferred objects (e.g. animations, other AJAX requests).
Furthermore, you can register as many .done() callbacks as you like, and .fail() callbacks too, without ever having to change updateUser().
The A in ajax is Asynchronous, which means that when the file loaded, the function that started it is done running. Try using jQuery Deferred: http://api.jquery.com/category/deferred-object/
Example:
jQuery("#button").click(function()
{
for(var i = 0;i < data.length; i++)
{
updateUser(data[i]).done(function(result) {
alert(result); //prints 'undefined'
});
}
});
function updateUser(user_id)
{
return jQuery.ajax({
url:"/users/update/"+user_id,
type:"GET",
async: false,
success: (function(data){
...
})
});
}
The function that called the success function is the Ajax request and not the UpdateUser function. So obviously when you return it it will return back from the success callback but not to the UpdateUser function..
Also since the ajax is Asynchronous , buy the time the callback is executed it will come out of the UpdateUser function.. !
pretty sure what is happening (not an expert) but you are returning 'data' for your annonomys function in success and not your whole updateUser function
function updateUser(user_id)
{
var retData;
jQuery.ajax({
url:"/users/update/"+user_id,
type:"GET",
async: false,
success: (function(data){
//if I alert "data" here it shows up correctly
//but if i try to return it like below
//it does not get passed correctly
retData = data;
})
return retData;
});
But like i said, i am no expert.
Related
I'm not so much pro in javascript variable scopes and got stuck with one question.
If i have function which dose ajax call and then call my callback
function doAjaxFunc(param, callback)
{
$.ajax({
type: 'GET',
url: '/some/url/'+param,
success: function(data){
callback(data);
},
dataType:'json'
});
}
function someCallback1(ajaxResp){
// DO someting 1
}
function someCallback2(ajaxResp){
// DO someting 2
}
// exec
doAjaxFunc(1, someCallback1);
doAjaxFunc(2, someCallback2);
As ajax is async and it can be that sever will process param=1 case longer then param=2 is it possible that someCallback1 and someCallback2 will process not their responses. I mean callback argument value will be somehow mixed ?
If possible give some explanation details in answer
I mean callback argument value will be somehow mixed?
No. The callbacks will be called in completely separate invocations within scope of the originating AJAX success handler. There will be no cross-contamination of the data from either request.
Also, just as an aside, you can change this:
success: function(data){
callback(data);
},
To just this:
success: callback,
Check this example , i hope it is some helpful to understand scope in JavaScript
var isFirstCall=false;
function doAjax(param)
{
if(!isFirstCall)
{
//for example after do ajax
var millisecondsToWait = 1000;
setTimeout(function() {
console.log(param);
}, millisecondsToWait);
}
isFirstCall=true;
console.log(param);
}
doAjax('first call');
doAjax('second call');
I am relatively a newbie to jquery and ajax and am trying to use the concept of deferrals and promises to solve this problem I have.
I would like to do the following:
Call a list of URLS and process the result returned from the urls. I would like to first process the results in parallel, and then combine the processed results to give me a final result.
Th pseudo-code is as follows:
var deferredAjaxCalls = [];
for (var i = 0; i < jobsListLength; i++) {
deferredAjaxCalls.push(
$.ajax({
url:"/myurl",
method:"POST",
contentType:"application/json",
dataType:"json",
data:mydata,
success:function(result){
//Some code here that is performance intensive
}
});
}
$.when.apply(this,deferredAjaxCalls).done(function(){
for (var k=0; k< arguments.length;k++){
//combine the results of the individual results of the
// success part of all the ajax calls and execute some more
//code synchronously
}
}).fail( function (jqXHR, status, error) {
//Log failed status
});
Initially, I moved all of the code from the success part inside the $.when.apply().However, this resulted in very slow performance as there is a lot of intensive computation that is now executed synchronously. So I am looking for a way to execute part of the code independently, and the final piece synchronously
I did read about using promises, but could not find any example where promises are used with an array of ajax calls with intermediate processing before finally synchronising in the when.apply() block
What would be a good way to solve this problem?
Thanks!
Starting with an array jobsList, you probably want something like this :
var deferredAjaxCalls = jobsList.map(function(job) {
return $.ajax({
url: "/myurl",
method: "POST",
contentType: "application/json",
dataType: "json",
data: mydata
}).then(process);// where `process` is a function that accepts $.ajax's (data, textStatus, jqXHR) and returns a *single* value/object - the result of the processing. This will standardise the data delivered below by $.when() to its success handler.
});
$.when.apply(null, deferredAjaxCalls).then(function() {
// Due to `.then(process)` above, `arguments` are guaranteed to comprise one arg per ajax call.
// Otherwise you potentially have the problem reported here - http://stackoverflow.com/questions/12050160/
for (var k=0; k<arguments.length; k++) {
// Combine the results of the individual results of the success part of all the ajax calls and execute some more code synchronously.
}
// In this function deliver an error by returning `$.Deferred().reject(new Error('myReason'))`
return combined_result;
}, function(jqXHR, status, error) {
// This hander will receive multiple $.ajax() params, which are best normalised into a single Error object.
return new Error(status); // similar to .then(process) above, reduce $.ajax's error args to a single "reason".
}).then(null, function(err) {
// All errors delivered by code above arrive here as a js Error.
// But please note that, in jQuery <v3.0, any uncaught errors above will genuinely throw (to the console).
console.log(err.message);
});
You can try using deferreds:
var req_responses = [];
var deferreds = [];
for(var i in jobs) {
deferreds[i] = new $.Deferred();
}
for(var i in jobs) {
(function(i) {
$.ajax ({
url: ".",
type: "POST",
dataType: "json",
done: function(response) {
//process the response
req_responses[i] = response;
deferreds[i].resolve();
}
});
})(i);
}
$.when.apply(deferreds).then(function(os) {
//all the responses are in req_responses
//finish processing
alert("done");
});
I have read this stackoverflow post several times How do I return the response from an asynchronous call?. For some reason, I just do not get it. Could someone post the example in the question here as an actual full working solution instead of the step by step guidance provided in section "2. Restructure Code" of the post which I am finding very confusing.
function foo() {
var result;
$.ajax({
url: '...',
success: function(response) {
result = response;
// return response; // <- tried that one as well
}
});
return result;
}
var result = foo(); // always ends up being `undefined`.
The success function is a callback, meaning it can be called whenever. In this case, it is being called after the ajax call, and return result; is being called before the ajax call, meaning result is not assigned before returning it, which is why it's always undefined.
One way I like to fix this problem is by passing my own callback into the foo function then calling it when I receive the data, like this:
function foo(callback) {
$.ajax({
url: '...',
success: function(response) {
callback(response) // <-- call it here
}
});
}
foo(function(data){
// use your data here
});
As it stands right now, you are returning result almost immediately from foo. The $.ajax() is called and the function immediately moves on to return result, which is undefined at that point; finally, when the ajax call is complete, you set result = response, but the function has long been complete (i.e., return result never happens again).
This is why asynchronous calls typically work with callbacks or promises. These are where you do your work after an asynchronous call completes. In your example, you could use promises, like:
function foo() {
return $.ajax({
url: '...'
});
}
And then call it like:
var result;
foo().done(function(response) {
result = response;
});
Or, you could do it with a callback, like:
function foo(callback) {
return $.ajax({
url: '...',
success: callback
});
}
And call that like:
var result;
foo(function(response) {
result = response;
});
Since ajax requests are done asynchronously, the browser will continue executing code and will only come back to your callback (under success:) when the request is finished (and successful).
This means that if you have code that is dependent on the request's response, you'll have to encapsulate it inside your callback in order to make sure that it won't execute beforehand.
$.ajax({
url : '...',
success : foo
});
function foo(response) {
console.log('This executes AFTER the request finished');
// do your thing with the response
}
console.log('This executes BEFORE the request finished');
I have a javascript function which supposed to check whether a task is completed.
When the task is completed there is a completion record in a file on the server.
The function supposed to make recursive calls to the server with some delay (potentially increasing) till it gets the completion record in the file.
The code given below makes excessive calls to the server with interval less than a second
example from Web Console:
[20:06:21.202] [20:06:21.563] [20:06:21.990]
But the task becomes competed on variable waittime value getting equal to max_waittime .
Though for a test case overall output is as expected, something is wrong with the function.
Where I'm wrong?
function check_status(time,div_id,filename) {
var status =0;
var waittime=time;
var max_waittime=11000000;
if (waittime < max_waittime){waittime=waittime+1000000; }
$.ajax({
type: "GET",
async: false,
url: "code_on_server_checking_file.php",
data: "f="+filename,
dataType: "text",
success: function(content) {
if (content ) {
// stuff related to output of the result
....
return status=1;
}
else {return status=0;}
}
});
if (status == 0 && waittime < 20000000){
setTimeout(check_status(waittime,div_id,filename),waittime);
}
else {alert('check_status passed!'+status+'|'+waittime);}
}
You need to pass check_status to setTimeout, not the value returned by invoking check_status(...). Since you need to pass parameters to check_status, use an anonymous function:
setTimeout(function () {
check_status(waittime, div_id, filename);
}, waittime);
You are calling the function instead of giving it as a reference to setTimeout. Wrap your function call in an anonymous function. Also, it would be better to simply set up the call in the ajax callback if needed rather than using a synchronous call. A synchronous call will tie up your browser.
function check_status(time,div_id,filename) {
$.ajax({
type: "GET",
url: "code_on_server_checking_file.php",
data: "f="+filename,
dataType: "text",
success: function(content) {
if (content ) {
// stuff related to output of the result
}
else {
time += 1000000;
if (time < 20000000) {
setTimeout( function() { check_status( time, div_id, filename); }, time );
}
}
}
});
}
"recursive calls to the server"? No, I don't think you want that.
If you go three deep, var max_waittime=11000000; will be created and initialized three times.
Maybe you can set the timeout value for the ajax call (ajax settings)
http://api.jquery.com/jQuery.ajax/
First of all, it looks like you don't understand that the ajax call is an asychronous call. Calling it just starts the networking operation and then the rest of your code continues executing. Some time later when the networking operation completes, your success function is called.
The ONLY place you can operate on the results of the ajax call is in the success function. You can't return a value from the success function and expect that to go anywhere. The only place that goes is somewhere inside the ajax code where it's dropped. If you need to do something with the results of the ajax call, then you need to either do that operation right in the success function or call some other function from the success function and pass it the returned data.
These are the parts of your code that do not work:
There's no point in returning the status value from the success function. It doesn't go anywhere except into the ajax function where the return value is just dropped.
This line of code if (status == 0 && waittime < 20000000){ is not doing what you want. Because the ajax call is asynchronous, the value of status has not yet been set by the ajax call when this line of code runs. Thus, it's ALWAYS 0 so your logic never works. You need to move this logic inside the success handler.
As others have said, your parameters to setTimeout are not right. You have to pass a function to setTimeout, not the results of executing a function.
This is the code I would suggest:
function check_status(time, div_id, filename) {
var max_waittime=11000000;
if (time < max_waittime){
time=time+1000000;
}
$.ajax({
type: "GET",
async: false,
url: "code_on_server_checking_file.php",
data: "f="+filename,
dataType: "text",
success: function(content) {
if (content ) {
// stuff related to output of the result
if (time < 20000000){
setTimeout(function() {check_status(time, div_id, filename)}, time);
}
}
}
});
}
Note that all handling of the ajax result is done in the success function and we pass an anonymous function to setTimeout that re-calls check_status after a time delay. This is not actually recursion (as others mentioned) because setTimeout allows check_status to return before it's called again some time later.
This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 4 years ago.
The function I called inside jquery returns undefined. I checked the function and it returns correct data when I firebugged it.
function addToPlaylist(component_type,add_to_pl_value,pl_list_no)
{
add_to_pl_value_split = add_to_pl_value.split(":");
$.ajax({
type: "POST",
url: "ds/index.php/playlist/check_folder",
data: "component_type="+component_type+"&value="+add_to_pl_value_split[1],
success: function(msg)
{
if(msg == 'not_folder')
{
if(component_type == 'video')
{
rendered_item = render_list_item_video(add_to_pl_value_split[0],add_to_pl_value_split[1],pl_list_no)
}
else if(component_type == 'image')
{
rendered_item = render_list_item_image(add_to_pl_value_split[0],add_to_pl_value_split[1],pl_list_no)
}
}
else
{
//List files from folder
folder_name = add_to_pl_value_split[1].replace(' ','-');
var x = msg; // json
eval('var file='+x);
var rendered_item;
for ( var i in file )
{
//console.log(file[i]);
if(component_type == 'video')
{
rendered_item = render_list_item_video(folder_name+'-'+i,file[i],pl_list_no) + rendered_item;
}
if(component_type == 'image')
{
rendered_item = render_list_item_image(folder_name+'-'+i,file[i],pl_list_no) + rendered_item;
}
}
}
$("#files").html(filebrowser_list); //Reload Playlist
console.log(rendered_item);
return rendered_item;
},
error: function()
{
alert("An error occured while updating. Try again in a while");
}
})
}
$('document').ready(function()
{
addToPlaylist($('#component_type').val(),ui_item,0); //This one returns undefined
});
The function addToPlaylist doesn't return anything. It makes an asynchronous request, which eventually executes a callback function, which returns something. The original addToPlaylist function is long done and returned by the time this happens though, and the callback function returns to nobody.
I.e. the success: function(msg) { } code executes in a different context and at a later time than the surrounding addToPlaylist function.
Try this to see it in action:
function addToPlaylist() {
$.ajax({
...
success : function () {
alert('second'); // comes after 'first'
return null; // returns to nobody in particular
}
});
alert('first'); // comes before 'second'
return 'something'; // can only return here to caller
}
You're making your request via AJAX, which by definition is asynchronous. That means you're returning from the function before the AJAX request completes. In fact, your return statement is meaningless as it returns from the callback function, not your addToPlaylist function.
You have a couple of choices. The first one is better.
First, you can work with the asynchronous nature of the AJAX request and pass a callback into your addToPlaylist method (much like you're passing in the anonymous callback to the ajax function) and have the AJAX callback, call that function instead of doing the return. That way your request completes asynchronously and doesn't lock up your browser while it's going on.
function addToPlaylist(component_type, add_to_pl_value, pl_list_no, cb )
{
...yada yada yada...
$.ajax({
...
success: function(data) {
...
if (cb) {
cb.apply(this, rendered_item );
}
}
});
}
Second, you can add the option aSync: false to the ajax call. This will force the AJAX call to run synchronously (essentially it just loops until the call returns then calls your callback). If you do that, you need to capture a local variable in your addToPlaylist function inside the callback and assign the value(s) to it from the callback. At the end of the addToPlaylist function, return this variable as the result.
function addToPlaylist(component_type, add_to_pl_value, pl_list_no )
{
...yada yada yada...
var result = null;
$.ajax({
aSync: false,
...
success: function(data) {
...
result = rendered_item;
}
});
return rendered_item;
}
I agree with deceze. What you need to do is perform the necessary action(s) for rendered_item in the success function rather than relying on getting something back from addToPlayList().