How can I access variable outside function in javascript? [duplicate] - javascript

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 9 years ago.
I have this code
function(config) {
items=[];
Ext.Ajax.request({
url : 'url',
success : function(resp) {
items = [a,b]
}
});
console.log(items);
return items;
},
I want the items array to be available in main function but its coming empty.

Even though this has been answered countless of times, I'll show you a quick example on what you need to do. In short, you can't access data recieved by an ajax call outside of the success handler. You'll need a callback:
function ajaxStuff(config, cb) {
Ext.Ajax.request({
url : 'url',
success : cb
});
}
var config = {};
ajaxStuff(config, function(resp){
//handle the ajax response here
});
http://jsfiddle.net/Yrd7r/

Related

From JQuery to JS variable [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 3 years ago.
I want the array of objects result (msg) that I get from AJAX into a JS variable (allEvents)
I thought it could be done like this:
let allEvents;
$.ajax({
method: "GET",
url: "https://someApiToGetData.com",
})
.done(function (msg) {
allEvents = msg;
});
console.log(allEvents);
I get Undefined as a result on the console. So the part allEvents = msg; wasn't as easy as I thought.
If I try console.log(msg) I get what I want. But I just want msg in that allEvents JS variable so I can handle the results.
Is there any way to get msg into allEvents?
An ajax request is asynchronous, which means that your last line will run before the ajax request has returned, that's why allEvents is undefined, if you modify your code to print allEvents inside done you'll see all events has the correct data.
let allEvents;
$.ajax({
method: "GET",
url: "https://someApiToGetData.com",
})
.done(function (msg) {
allEvents = msg;
console.log(allEvents);
});

Wait for a function to finish before assigning the return to a variable - JS [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 6 years ago.
I have a function that does a AJAX post request and returns the data from that request.
The problem is that when using the function the code won't wait for the function to return before containing.
How can I add a call back to a function call.
function apicall( data ) {
var props = {
data : data,
..
}
$.post( '/auth/login' , props )
.done(function( data ) {
var result = JSON.parse(data);
return result;
});
}
I then call the function below
var result = apicall( data);
I need to wait until apicall has finished before assigning the value to result
found the answer in this post: using deferred
function wait with return until $.getJSON is finished

Javascript function with AJAX call - return value after response [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 6 years ago.
Is this possible to return value from function which includes an ajax call after the call is executed? For example, in the example here, function1 and function2 both have ajax calls. I'm forced to specify async as false for both the requests as the value that is returned from the functions is setup in the success callback. Is there anyway to overcome this issue so that calls can still be asynchronous but the return values are fine?
$(document).ready(function(){
var abc = function1();
var xyz = function2();
});
function1()
{
var value = "";
$.ajax({
url: url,
async: false,
success: function(data) {
value = "value1";
}})
return value;
}
function2()
{
var value = "";
$.ajax({
url: url,
async: false,
success: function(data) {
value = "value2";
}})
return value;
}
You should process the asynchronously received data within the callback. Doing this synchronously is the bad way.

Javascript - Pass callback value to calling variable [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 7 years ago.
I have a function and a variable....
var imageURLs = retrieveRemoteImages(vinUrls)
if imageURLs !== undefined) {
// do something
}
function retrieveRemoteImages(urls) {
var imageURls = [];
processSpinnerActivity(START_IMAGES_IMPORT);
importImagesforSlideShow(REMOTE_IMAGES_URL, urls, function (images) {
if (images !== undefined) {
imageURls = images;
return imageURls;
}
})
return imageURls;
}
This does as intended ....
function importImagesforSlideShow(imagePath, urls, call_back) {
var functionName = 'importImagesforSlideShow'
$.ajax({
type: "POST",
url: LOCAL_PROCESSING_MODULE,
data: {data: [imagePath, urls, IMAGE_EXTENSION_QUALIFIER], functionid: functionName},
dataType:"json",
success: function (res) {
processSpinnerActivity(IMPORT_IMAGES_SUCCESS);
call_back(res);
},
error: function (err) {
processSpinnerActivity(IMPORT_IMAGES_ERROR);
console.log(err.message);
}
});
}
The callback works fine, but I am not able to pass the eventual value to imageURLs and I need to, as the next step cannot occur until it has a value.
Any ideas?
Thanks!
This is not a duplicate question, I have no issues with my AJAX returning the async value*
It's not possible like that, you are executing a piece of async code. So your code keeps running while their isn't any data yet. You have to process your data in a callback, for example like this:
function retrieveRemoteImages(urls, callback) {
processSpinnerActivity(START_IMAGES_IMPORT);
importImagesforSlideShow(REMOTE_IMAGES_URL, urls, callback);
}
retrieveRemoteImages(vinUrls, function(imageURLS) {
//do your stuff
});

Ajax response to be a return value of a function [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 8 years ago.
In the below piece of code I am not getting the locale in the second alert
if `value==null`
I assign its locale value. but do not get it at the end.
function getLocale(id) {
var locale="";
var value = localStorage.getItem(id);
if (value == null) {
$.ajax({
type: "POST",
url: "myUrl",
data: {"new" : id},
success : function(data) {
data = JSON.parse(data)
var id = data[0]["id"];
delete data[0]["id"];
localStorage.setItem(id, JSON.stringify(data[0]));
locale=JSON.stringify(data[0]);
alert(locale);//corrects value
}// end success
});
}else{
locale= localStorage.getItem(id);
}
alert(locale+"locale");//not have the value
return locale;
}
Its not because of the scope. It is because of the asynchronous behaviour of ajax call. Because the function will not wait for the success event of ajax.
If you want to return, you should use async:false in ajax. But it is not a good method of coding.
Or you should restructure your code with the asynchronous ajax. Instead of returning the value, call a function in the ajax success with desired id.
ajax request is an async process which means it has a different execution timing with your function returning a value.
the trick here is do not assume to have a return value in the scope of the function.
do all the process in the success call back function
success : function(data){
//do everything what you want to do with the response here
}

Categories