This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 7 years ago.
I have the following code
function test(){
var api_url = "/Test/";
api.CFClient.load(api_url,function(success){
success.images; // Object with images
},function(error){
});
// More code to use the images returned.
I am basically unable to get the images from the success function. If i execute my code within the success function i am able to access the returned object. How do i store the returned object in a variable so i can use that object in my parent function and not the success function ?
I presume api.CFClient.load is asynchronous, and in that case you can't access success.images immediately in the test() function after invoking the load function. It will be available at some unknown time in the future, when the ajax request has completed. You'll have to invoke a different function from within your success callback and do whatever you need to do with success.images there, or else do what you need to do directly in the success callback function.
You need to account for the success function being asynchronous. You won't be able to use the returned images until the api call is complete. When it is, you can call another function and pass the images.
function test(){
var api_url = "/Test/";
api.CFClient.load(api_url,function(success){
useImages(success.images);
}, function(error){
});
function useImages(images) {
// do something with images here...
}
SO is full of errors like this(asynchronous workflow), just google for...
function test(){
var api_url = "/Test/";
function useImages(err, images) {
if (err) return console.error(err);
console.log(images);
}
api.CFClient.load(api_url,function(success){
useImages(null, success.images);
},function(error){
useImages(error);
});
}
Related
This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 7 years ago.
Right now I have three files, two javascript files and one html file that will call upon these two javascript files. Inside my first javascript file, let's call it part1.js, I have this content:
var dataval;
$.get('example.cgi', function(data){
dataval = data;
});
Inside part2.js, I am trying to call on this dataval value. But it is not working, as I am assuming that dataval is inside the get function and is therefore a local value. Is there anyway I can grab that value? My html file is calling on both of these javascripts. Is there anyway I can access that variable?
Thanks!!
There is a problem here with asynchronous calls. You should either use a callback function or make use of the jquery promise capability.
In your part1.js, you should instead define a function:
function callCgi(callback) {
$.get('example.cgi', callback); //Callback will receive the data.
}
and then use it in part2.js:
callCgi(function(data) {
//do something with data.
});
Or with promises:
function callCgi() {
return $.get('example.cgi');
}
and then use it in part2.js:
callCgi().then(function(data) {
//do something with data.
});
This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 8 years ago.
I've clearly been writing too much CoffeeScript, as I am now realizing I do not have even a basic understanding of scope in pure JS.
After playing for a while, I cannot figure out the problem with the following--
$(document).ready(function() {
var myUrl = "http://notimportant.com/"
var photos = getPhotos(myUrl);
console.log(photos); //undefined
});
function getPhotos(url) {
var a;
$.get(url, function(data) {
a = data["photoset"]["photo"];
console.log(a); //my object
});
return a;
}
If I put a console.log(a) statement on the line right below 'var a = data["photoset"]["photo"];' it shows that it properly makes the GET request I'm looking for. But I'm finding it impossible to pass that object back to my main block of code, where I want to manipulate it.
Thanks in advance.
The reason photos is undefined is not because of scopes. Its because $.get is executed asynchronously. $.get() returns jqXHR object instead of an HTTP response.
onSuccess callback should be passed to getPhotos() in order to make it work correctly. Alternatively when().then() construct could be used.
$(document).ready(function() {
var myUrl = "http://example.com/";
getPhotos(myUrl, renderCatPhotos);
});
function getPhotos(url, onSuccess) {
$.get(url, onSuccess);
}
function renderCatPhotos(data) {
var a = data.photoset.photo;
console.log(a); // a is always available
}
note: you might not even need getPhotos function. You can simply $.get(url, onSuccess); in $(document).ready() instead.
Its not a matter of scope, its a matter of that you are returning an undefined variable before the $.get defines it. Consider making photos a global, then setting it in the $.get success function instead of setting it to 'a'. Inside the success function, you can then issue calls to other functions that would control displaying/processing the photos.
This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 8 years ago.
The title might be a bit strange, but I'll try to explain.
I do an API call to validate some data. For this I use the following function:
function validateAddress(address) {
var validationURL = "/api/validateAddress/"+address;
$.getJSON(validationURL, function(data, textStatus, jqXHR){
if (textStatus === "success") {
return data.isValid
}
}));
}
// And then in other parts of the code I want to do something like:
if (validateAddress(address)) {
// do something awesome right here..
}
The problem with this is of course that it is an async call, which causes validateAddress() to not return anything, because it ends before the API call has returned any result.
So how can I actually make validateAddress() return the result of the api call? All tips are welcome!
You have few options:
you can either pass parameter to jQuery ajax functions to make the call synchroneous (you can't use getJSON though, you need to use $.ajax directly and pass it async: false)
you can pass callback into the validateAddress function as second parameter that you'll call when the request finishes
you can return the return value of $.getJSON call from the function validateAddress, since it's a promise, you can attach your code to that with the use of .done() (example of this is here http://api.jquery.com/jQuery.getJSON/#jqxhr-object)
How about something like:
function validateAddress(address) {
var validationURL = "/api/validateAddress/"+address;
return $.getJSON(validationURL);
}
and then use it like:
validateAddress("myaddress").done(function(response) {
// do my stuff here
});
This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 8 years ago.
I'm calling a C# api through Jquery AJAX. I am able to loop through all of the data and print each in the console; however, I am not able return the data to a variable (var x) so that it contains all objects returned from the api call.
This is my code thus far:
var uri = 'api/products';
function test(){
// Send an AJAX request
$.getJSON(uri)
.done(function (data) {
// On success, 'data' contains a list of products.
var info = {};
$.each(data, function (key, item) {
// Add a list item for the product.
console.log(item);
info.append(item);
});
return info;
});
}
var x = test();
I have tried to just simply skipping the $.each() and returning data, with no luck.
Should I be using a method other than append? Or is there a way to just simply return data?
Thanks.
.done() is a promise (http://api.jquery.com/promise/), which takes a callback function. The callback function is void; nothing consumes its return...and the return in your code is the return for the (anonymous) callback function, not for test(), which is why you're seeing no value come out.
This is an asynchronous pattern. That means test() is going to return immediately, not waiting for the AJAX call to complete, and there's no value yet to put into x! The AJAX response will arrive later, at some unknown time. The purpose of the callback function is to allow you to (at that time!) do whatever it is you intend to do with the value you receive. You haven't shown us what that is in this example, but you're going to need to restructure it to happen after the promise is fulfilled.
This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 8 years ago.
I'm using the jQuery function $.getJSON to get some data from the server side and here is the code:
function (){
$.getJSON("someURI",function(result){
//this alert works fine
alert(result.msg)
});
// this prints the data as undefined
alert(result.msg);
}
how to change the scope of "result" returned from $.getJSON in order to make it global.. to make the second alert prints its value not to be undefined ??
You can't. AJAX is asynchronous meaning that you can access the result variable only inside the success callback. You could make it global, but remember that the line immediately following the $.getJSON call will be called much before the success callback executes rendering it useless.
So no global variables, consume the results of an AJAX call inside the callback:
function () {
$.getJSON('someURI', function(result){
// only here you can hope to consume the results of an AJAX call
alert(result.msg)
});
}
That's how AJAX works. The A in AJAX stands for asynchronous.
This is an asynchronous call.. So you must wait till the server responds...
In your case, the outer alert will be undefined as the server hasn't responded yet...
Also, the scope of result is limited to callback function, it's inaccessible...
You can do it like this though:
var myJSON;
var serverResponded = 0;
function () {
$.getJSON("someURI", function (result) {
//this alert works fine
myJSON = result.msg;
serverResponded = 1;
});
setTimeout(function () {
if (serverResponded) {
alert(myJSON);
}
}, 500);
}
The $.getJSON call is a shortcut to an Ajax call, and “Ajax” stands for “Asynchronous JavaScript and XML”.
Let's suppose you add var globalResult and that you perform a globalResult = result; in your success function. So, when you do a call to globalResult outside the callback, globalResult won't be assigned yet. So, if you really have to process it outside, you can check if it's assigned with a function called setInterval, but this is going too far.
save it into another variable something like this
function (){
var something;
$.getJSON("someURI",function(result){
//this alert works fine
alert(result.msg)
something = result
});
if you want it to be scoped outside your function wrapper, do something like this
var something;
function (){
$.getJSON("someURI",function(result){
//this alert works fine
alert(result.msg)
something = result
});