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));
});
Related
This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 3 years ago.
In basic terms I am trying to make a cross domain AJAX call using JSONP. The JS and PHP files need to be on a different domain. I can't seem to get the returned data back to the original function.
To explain how the page works. A user will enter something into an input box. e.g. Surname.
Input and search.
After the user clicks search a the searchClick() function is called. This function takes the text the user has inserted into the input box and calls another function called getInfo().
function searchClick() {
var jsonOfData = getInfo($('#searchInput').val());
console.log(jsonOfData );
}
The getInfo() function has to be in a JS file on a different domain.
function getInfo(surname) {
$.ajax({
url: "https://www.otherdomain.com/api/lookup.php",
dataType: 'jsonp',
crossDomain: true,
data: {
surname: surname
},
success: (data) => {
console.log(data); // This works
return data; // This doesn't
}
});
}
This ajax call goes off to my PHP page and does a search on the database. It then created a JSON array and sends it back. From my research instead of ending the file with the usual echo json_encode($array); I ended the file with:
echo $_GET['callback'] . "(" . json_encode($responseArr) . ")";
This is the point at which I have my problem. As you can see, in the AJAX success function, the data is successfully displayed and logged to the console but I can't return it back to the original jsonOfData variable.
I hope this makes sense and i'll be so thankful to anyone who can help me out.
What you're trying to do won't work, because the $.ajax calls works asynchronously.
Instead of work with the return of the function call at this point:
var jsonOfData = getInfo($('#searchInput').val());
Try to build your logic inside the success function of your $.ajax call.
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 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?
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:
How do I return the response from an asynchronous call?
(41 answers)
Closed 8 years ago.
I am calling ajax in one function and the result should be caught in another function.
It is better explained below
function myMain(){
var test = myWPackage();
alert(test);
}
function myWPackage(){
var tender_number = "TENDER_TEST-123";
//calling ajax function
$.ajax
({
url: "getWorkPackage.php",
type: "POST",
dataType: 'json',
data: {source1 : tender_number},
cache: false,
success: function (work_package)
{
return work_package[0];
})//ajax ending
}
The database if connected and the value is coming if i replace return with alert in myWPackage so there is no issue with database or the data coming.
When i call myMain() function it gives "UNDEFINED". Can anyone let me know what am i doing wrong? I am trying to ge the value from ajax to test.
thank you in advance.
I think the problem is of synchronization , Because Ajax in jquery if not synchronize
Try this link