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);
});
Related
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.
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
});
This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 7 years ago.
I'm trying to build a jQuery ajax function which is totally generic. It would receive all the data and even request type as parameters. After that it will substitute in the respective variables and build the request. Here is the code...
function server_request (type, url, dataType, data) {
var packet;
var response = null;
if (packet) {
packet.abort();
};
if (type == "get") {
packet = $.ajax({ type: type, url: url, dataType: dataType });
packet.done(function(returned_data){
response = returned_data;
});
}
return response;
response = null;
}
So I want the received data to be stored in an already declared variable called "response" and I want it to be returned for use in another place. Somehow its not working and it keeps returning the predefined value of the response variable. can someone help??
Ajax requests are asynchronous, so by the time you use response somewhere, it might now have value yet.
You should probably return the whole packet and do a packet.done() call where you need the response at.
function server_request (type, url, dataType, data, _callBack) {
var packet;
//var response = null; //not needed
if (packet) {
packet.abort();
};
if (type == "get") {
packet = $.ajax({
type: type,
url: url,
dataType: dataType,
callback: _callBack
});
packet.done(function(returned_data){
//this context is a new context, coming from the AJAX constructor
//response = returned_data; //this is assigning the data too late
return this.callback(returned_data);
});
}
//this context wont return anything because its not the AJAX context.
//return response;
//response = null;
}
When you create the ajax object, you can assign any kind of arbitrary data in the constructor (JavaScript rules because of this!) - So you define a callback property and assign the _callbackFunction you provided to that property.
In the packet.done context, you call the callback function and pass in the response data.
Your calling method would look like this.
server_request('type','url','datatype','data',
function(returnedData){
//now you can work with the returend data in the correct context.
});
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
}
This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 9 years ago.
I have a function which returns data:
function getData(){
return {result:[{},{},{}...]};
}
This function worked perfectly. Now I want to generate the data dynamically. I use the following method to generate the data, however it does not work out then:
function getData(){
$.ajax({
//...
async: false,
success: function(data, textStatus, jqXHR){
return {result:[{},{},{}...]};
}
});
}
Can some provide me some hints for this or point me to the right direction to do it? thank you.
You have to return the data from your outer function:
function getData () {
var data;
$.ajax({
//...
async: false,
success: function(data, textStatus, jqXHR){
data = {result:[{},{},{}...]};
}
});
return data;
}
However, you shouldn't be using synchronous AJAX requests. That'll freeze all execution until the request has completed.
Instead, return the promise returned by the $.ajax call, and use that in your calling code:
function getData () {
return $.get('/path/to/recourse');
}
getData().then(function (results) {
// use results here...
});
Never DO this(using async : false), it will block the browser thread till the response comes from the server which will freeze the user experience till the response comes back.
you are only returning from the inner function, not from getData
function getData(){
var result;
$.ajax({
//...
async: false,
success: function(data, textStatus, jqXHR){
result = {result:[{},{},{}...]};
}
});
return result
}
Then how to do it correctly... There are literally thousands of threads regarding this in SO itself... A famous one is How to return the response from an AJAX call