Return response from asynchronous call example - javascript

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

Related

Callback inside AJAX success

Im trying to add an optional callback inside an AJAX successful execution, but I can't seem to get the callback to run when I want it to.
heres and example of my AJAX code
function someAjaxFunction(hosturl, callback){
$.ajax({
type: "GET",
url: hosturl,
data: {'something': 'code' },
dataType: 'json',
success: function(html){
var arr = $.map(html, function(val) { return val; });
if(arr[0] != 'false'){
console.log('1');
console.log('2');
if (callback) {
console.log('calling the callback')
callback();
}
console.log('3');
}else{
console.log('fail')
}
}
});
}
here is the callback and example of how the AJAX is being executed
function thisIsACallBack(){
console.log("i'm a callback");
}
someAjaxFunction("some url", thisIsACallBack);
If I run this code the console outputs.
1
2
3
i'm a callback
I can even remove the callback if-condition all together and I would still get the same output.
Also is here a better way to handle my Ajax return currently my response wrapped inside a json object. If the database can't find the object I have to place 'false' inside an array and convert it to a json object before echoing it back to ajax.
Couse you have to pass your callback as string to your function
someAjaxFunction("some url", thisIsACallBack); // <-- Wrong thisIsACallBack will be triggered after someAjaxFunction as some separate function call
like this
someAjaxFunction("some url", "thisIsACallBack()"); // <- Correct way
// Then call eval( callback ); inside Ajax success
....
success: function(html){
...
eval( callback );
}
your problem was that in case of this code someAjaxFunction("some url", thisIsACallBack); it was triggering someAjaxFunction then thisIsACallBack function as you written someAjaxFunction name not as string
UPDATE
if you have to pass params to your callback your option is
someAjaxFunction("some url", function(param1){
thisIsACallBack(param1)
); } );
...
success: function(html){
...
callback( yourArray );
}
JavaScript has many ways how you can pass callbacks depends on your need

Recursive function in javascript and ajax

I'm trying to do a little web in JavaScript + Ajax and I want to do it recursively. I've never used ajax before and the problem is I don't know to finish functions. The code looks like that:
var cont = 0;
var function1 = function (query) {
$.ajax({
url: '...',
data: {
.
.
.
},
success: function (response) {
instructions;
function2(param1, param2);
}
});
};
var function2 = function (query, param2) {
$.ajax({
url: '...',
data: {
.
.
.
},
success: function (response) {
instructions;
function3(param1, param2, param3);
}
});
};
var function3 = function (query, param2, param3) {
if (cont == 2) {
console.log("finish");
return;
}
var test = $.ajax({
url: '...',
data: {
.
.
.
},
success: function (response) {
if (...) {
cont++;
instructions;
var audio = new Audio(...);
audio.play();
audio.onended = function () {
instructions;
function3(query, param2, param3);
return;
};
} else {
instructions;
function3(query, param2, param3);
};
return;
}
});
return;
};
document.getElementById('search-form').addEventListener('submit', function (e) {
e.preventDefault();
function1(document.getElementById('query').value);
}, false);
So basically, when cont == 2I try to get out of javascript function3 with return; but some part of the program ( I don't know if the success: function (response) or the full javascript function3 ) is still running and instructions are being executed.
How could I solve this?
First off, the way to do this properly is to make use of jQuery's deferred objects.
As you have probably noticed, the program doesn't simply wait at the ajax request, and then proceed to the 'success' handler. This is because Javascript uses a non-blocking/waiting model. So you call $.ajax({params,...}), this sends the request, but whatever's after this will then immediately run, without waiting. Then, once the top level function has finished executing and nothing else is running, the response can be processed, and the 'success' handler is invoked.
So how to do this stuff properly? Start by arranging your request functions like this:
function doRequest1() {
return $.ajax({
url: '...',
data: {
.
.
.
}
});
}
function doRequest2(parameter) {
return $.ajax({
url: '...',
data: {
.
p: parameter
.
}
});
}
Notice that we aren't providing a success handler, but we are returning the value that $.ajax returns. This is a deferred object which is used to represent a request which has been sent, but for which a response hasn't been received/handled. You can attach a handler to the object like this:
var r1 = doRequest1();
r1.then(function() {
// Do stuff on success...
});
A nice thing about these objects is that they can be chained using 'then'.
'then' accepts a function which takes the value of the old request and produces a new request to do next:
var allRequests = doRequest1().then(function(result1) {
return doRequest2("hello");
});
The 'allRequests' variable is now a deferred object representing the result of doRequest2. How do you get this result? You use 'then()', just like any other deferred:
allRequests.then(function(result) {
alert("All requests completed. Result of last one: " + result);
});
Make sure that you understand how the result from 1 request can be used to set the parameters for the next one, or even decide which request to make next.
If you don't need one request's result to determine the next, rather, you just want to run a number of requests and wait for them all to complete, you can use a shortcut, 'when':
$.when(doRequest1(),doRequest2(), doRequest3()).then(function(result1,result2,result3) {
// All done
});
Another nice thing about deferreds is that they can be cancelled:
allRequests.abort();
Using the above, hopefully you can see how to restructure your code so you get a sequence of requests with a function to run after all 3 have completed.
Watch the value of your global variable cont through the flow of your program. It may be that it is (never) equal to 2 when function3() is called and that is why your program continues.

Passing jQuery ajax value back to calling JavaScript function

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.

Javascript Scope Issue

I'm trying to get this function to work. I think the function is pretty self explanitory:
function FileExists(path){
var result = false;
$.ajax({
url: "http://mydomain.com/"+path,
type: "HEAD",
success:
function(){
result = true;
}
});
return result;
}
I need the anonymous function that is called upon success of the ajax post to set the variable "result" that was defined inside the FileExists function to true so that I can return that value from the FileExists function. I think I need a closure for this but they confuse the hell out of me.
Please help!
Thanks!
It's not a scoping issue, but rather because $.ajax is asynchronous, meaning that FileExists will return before $.ajax will complete. What you should be doing is to move all code that depends on result to inside the success callback.
Ajax calls are by default asynchronous, you can either use a callback function:
$.ajax({
url: "http://mydomain.com/"+path,
type: "HEAD",
success: function(){
callback(true);
}
});
Or make the call synchronously.
$.ajax({
async: false,
url: "http://mydomain.com/"+path,
...

Function inside jquery returns undefined [duplicate]

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().

Categories