This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 6 years ago.
Im having issues getting my data passed back to an external variable. I know the ajax request works but its not passing it in the manner that i need.
here is a exact method in my class
function(amount,symbol=''){
var current_rate = '';
var url = "https://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20html%20where%20url%3D'https%3A%2F%2Fwww.google.com%2Ffinance%2Fconverter%3Fa%3D"+ amount +"%26from%3DNGN%26to%3D"+ symbol +"'%20and%20xpath%3D'%2F%2Fdiv%5B%40id%5D'&format=json&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys";
var get_rate = $.ajax({
url: url,
method: "GET"
}).complete(function(data){
current_rate = data.responseJSON.query.results.div.span.content;
}).fail(function( jqXHR, textStatus ) {
alert( "Request failed: " + textStatus );
});
return current_rate;
}
Ive edited the code for simplicity. but heres the full script . I just need to know how to pass the data from the request back into the 'Current_rate' variable
Your function returns current_rate = '' because that's the value of current_rate when the function ends. It ends before the asynchronous call completes!
This part:
$.ajax({
url: url,
method: "GET"
}).complete(function(data){
current_rate = data.responseJSON.query.results.div.span.content;
})
Will set current_rate when the AJAX call returns, which will be long after your function returns. You have to think of $.ajax() as scheduling the request (and the code that runs when the request is complete). It doesn't block or wait for that to happen - your function just continues on.
The best solution here is to return the promise that $.ajax() returns, so your calling function can wait on it:
function(amount,symbol=''){
var url = "https://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20html%20where%20url%3D'https%3A%2F%2Fwww.google.com%2Ffinance%2Fconverter%3Fa%3D"+ amount +"%26from%3DNGN%26to%3D"+ symbol +"'%20and%20xpath%3D'%2F%2Fdiv%5B%40id%5D'&format=json&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys";
return $.ajax({
url: url,
method: "GET"
});
}
In order to use this, call the function like this:
get_current_rate(1000,'CAD').complete(function(data) {
// do something with the returned data
});
See the documentation for the jQuery Deferred object. See also this post, which contains an excellent (long!) explanation of the problem and various solutions: How do I return the response from an asynchronous call?
Related
This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 3 years ago.
My current code is :
var dataReceiveString = $.ajax({
url: "getDataReceiveString.php?"+param,
dataType: "text",
async: false
}).responseText;
// code that make use of dataReceiveString ;
The obvious choice of changing false to true does not work.
How should the code be rearranged ?
Also to add a waiting circle gif animation while javascript do ajax call to php.
edit : question is different from Execute function after Ajax call is complete
as avoiding use of async:false.
edit : question is different from
How do I return the response from an asynchronous call?
as it's too generic and not targetted to my question.
If you want to make it sync you can always rely to async functions:
async function doAjax(args) {
let result;
try {
result = await $.ajax({
url: ajaxurl,
type: 'POST',
data: args
});
// code that make use of dataReceiveString
return result;
} catch (error) {
console.error(error);
}
}
This question already has answers here:
Jquery call another function after ajax in loop is done
(1 answer)
How do I return the response from an asynchronous call?
(41 answers)
Closed 5 years ago.
I am writing a code in which user checks multiple check boxes and those users assign to the selected division. I am using $.post function in a loop of check boxes. Everything is working fine and checked users are being assigned to the selected division. Now, the issue is that I want to print a response after $.post function but everything I write after this post function, javascript executes it before that function and that's why, I am unable to print the response. Please check the below code for your convenience and suggest a possible solution.
Thanks a lot
function assign_user(div_id){
//alert(div_id);
var favorite = [];
$.each($("input[name='user']:checked"), function(){
value = $(this).val();
$.post("../db/assign_user.php",{div_id:div_id,value:value},
function(x){
});
// I want to print final response here but it executes before post function
});
}
Ajax requests are asynchronous. They are sent to the server, then the javascript continues on without waiting for a response. If you type your Ajax request like:
$.ajax({
url: "../db/assign_user.php",
type: 'POST',
data: {div_id:div_id,value:value},
success: function(data){
alert(data);
}
});
then in the success function, you can handle or alert the response.
This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 7 years ago.
My alert shows an "Undefined" with the following code:
var nonce = (function () {
$.ajax({
url: site_url + '/api/get_nonce/?controller=user&method=register&apikey=XXX&callback=?',
type: "GET",
dataType: 'json',
success: function(data){
nonce = data.nonce;
}
});
return nonce;
})();
alert(nonce);
The JSON is:
?({"status":"ok","controller":"user","method":"register","nonce":"XXX"})
What I'm doing wrong?
Ajax calls are asynchronous. At the point you are doing the return nonce; the result hasn't arrived yet - or at least isn't guaranteed to.
You'd need to put the alert(nonce);, and anything else you want to do with the result, inside the success handler of the Ajax call.
In the long run, you also want an error callback to handle when something goes wrong.
This question already has answers here:
Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference
(7 answers)
Closed 7 years ago.
I'm writing a chrome extension which makes a call to google translate api. Once I get the translated word I'd like to add it into an array but I believe it's async and I'm not sure how to pass it to the array so that it's available on the main thread.
var translatedWords = ["hola"];
var text = "what";
var key="******************";
var source="en";
var dest="es";
$.ajax({
type: "GET",
url: "https://www.googleapis.com/language/translate/v2key="+key+"&source="+source+"&target="+dest+"&q="+text
}).done(function(response) {
//SET Translated word
var WordTranslated = response.data.translations[0].translatedText;
//populate into array
translatedWords.push(WordTranslated);
}).fail(function(response) {
console.log("FAILURE: " + JSON.stringify(response));
});
console.log("translatedWords " + JSON.stringify(translatedWords));
And this outputs
translatedWords ["hola"]
where it should now be
translatedWords ["hola","que"]
How can I accomplish this? Thanks!
This isn't an issue with the chrome extension, this is an issue with callbacks in an ajax request. When you call $.ajax, the response is asynchronous. This means that it doesn't wait to return until it returns to keep executing your method. So your order of operations is:
Make ajax call
Run console.log statement
Ajax statement returns, runs success
You need to put your logic that depends on the results into the actual success callback, like this:
$.ajax({
type: "GET",
url: "https://www.googleapis.com/language/translate/v2key="+key+"&source="+source+"&target="+dest+"&q="+text
}).done(function(response) {
//SET Translated word
var WordTranslated = response.data.translations[0].translatedText;
//populate into array
translatedWords.push(WordTranslated);
console.log("translatedWords " + JSON.stringify(translatedWords));
//Any other logic here as well
}).fail(function(response) {
console.log("FAILURE: " + JSON.stringify(response));
});
This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 9 years ago.
I have two web services calls I need to make from my JQuery 1.9.1 app. I need the results from the first one before I make the second call.
It appears that my getJSON requests do not block the thread. I'm told that javascript is not multi-threaded, so how do I block between these server calls?
jQuery's ajax functions all return a jqXHR object that implement the Promise interface.
Instead of blocking an asynchronous request (and everything else), nest your requests like so
$.ajax({...})
.done(function( data ) {
// second request
$.ajax({...});
});
Well, you don't need to block threads, that's old school.
You have two options:
Make the ajax call syncronous.
Cascade the ajax calls, so the second is made only once the first one is completed.
I recommend the second approach, because that is the right way to do it.
/* Call 1 */
$.ajax({
url: 'first url to call',
data: 'first data sent to the server',
success: function (results1){
// Do something with the results
/* make the second call */
$.ajax({
url: 'sencond url to call'
data: 'second data sent to the server'
success: function(results2){
// Do something when all completed
}
});
}
});
Call your 1st ajax request in async false mode to server
$.ajax({
url: Url,
dataType: 'json',
async: false,
data: myData,
success: function(data) {
//stuff
}
});