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
}
});
Related
I have a function that needs to either return true; or return false; which contains an ajax call that is the method for determining the conditional result based on the response.
My problem is scoping and I'm not sure how to get out of this one. If I setup as a callback, then the return statement lives within the callback function itself and doesn't execute within the main wrapper function.
How should this be setup to execute correctly? Do I need to completely restructure?
function() {
var response;
$.ajax({
dataType: 'jsonp',
url: 'https://apilayer.net/api/check?access_key=',
async: false,
success: function(json) {
response = json.score;
}
});
if (response == 1) {
return false;
}
};
dataType: 'jsonp',
async: false,
JSONP requests cannot be made syncronously, so async: false is ignored.
If you weren't making a JSONP request, then using async: false would still be a bad idea (the underlying feature it depends on is deprecated for good reason).
This means that you can't do what you want.
The answers to How do I return the response from an asynchronous call? describe strategies for dealing with this.
First of all, 'async = false' is not supported anymore so call will be async in nature.
Now, you have two options:
initialize conditional var i.e. response with some value. So even if
ajax response is not received, you will not face any error on if
condition.
put conditional statement inside callback.
If your condition is based on ajax response, then ideal way would be to put it inside callback function.
Hope it helps!
if you use async false the request will become synchronous and the code will not be executed until the request is completed. this will slow down the browser.
var response = $.ajax({
dataType: 'jsonp',
url: 'https://apilayer.net/api/check?access_key=',
async: false,
success: function(json) {
response = json.score;
}
});
GOAL: What I'm after is to get data from database and refresh main.php (more evident through draw_polygon) every time something is added in database (after $.ajax to submit_to_db.php).
So basically I have a main.php that will ajax call another php to receive an array that will be saved to database, and a json call another php to return an array will be used by main.php.
$(document).ready(function() {
get_from_db();
$('#button_cancel').click(function(){
$.ajax({
url: 'submit_to_db.php',
type: 'POST',
data: {list_item: selected_from_list},
success: function(result){
...
get_from_db();
}
});
});
function get_from_db(){
$.getJSON('get_from_db.php', function(data) {
...
draw_polygon(data);
});
}
});
In my case, what I did was a get_from_db function call for getJSON to actually get data from database, with the data to be used to draw_polygon. But is that how it should be done? I'm a complete newbie and this is my first time to try getJSON and ajax too to be honest. So my question: How does asynchronous work actually? Is there another workaround for this instead of having to call function get_from_db with getJSON (it isn't synchronous, is it? is that why it doesn't update the page when it isn't within a function?) All the time - like $.ajax with async: false (I couldn't get it to work by the way). My approach is working, but I thought maybe there are other better ways to do it. I'd love to learn how.
To make it more clearer, here's what I want to achieve:
#start of page, get data from database (currently through getJSON)
Paint or draw in canvas using the data
When I click the done button it will update the database
I want to AUTOMATICALLY get the data again to repaint the changes in canvas.
Since $.getJSON() uses ajax configurations, just set the global ajax configs:
// Set the global configs to synchronous
$.ajaxSetup({
async: false
});
// Your $.getJSON() request is now synchronous...
// Set the global configs back to asynchronous
$.ajaxSetup({
async: true
});
Asynchronusly does mean the Request is running in the background, and calls your function back when it got a response. This method is best if you want to have a result but allow to use your app within the request. If you want to have a direct response, take a look at a synchron request. this request will pause script execution until it got a response, and the user can not do anything until the response was recieved. You can toggle it via:
async: false,
So for example:
$.ajax({
url: "myurl",
async: false,
...
})
$.getJSON(), doesn't accept a configuration, as it says in the docs it's a shorthand version of:
$.ajax({
dataType: "json",
url: url,
data: data,
success: success
});
So just rewrite your request in terms of that and async:false will work just as you expect.
$.getJSON() is a shorthand notation for $.ajax() which can be configured to be synchronous (see jQuery.getJSON and JQuery.ajax):
$.ajax({
dataType: "json",
url: url,
data: data,
async: false,
success: function(data) {
...
draw_polygon(data);
}
});
Try to avoid synchronous calls though. Quote from jQuery doc (see async prop):
Cross-domain requests and dataType: "jsonp" requests do not support
synchronous operation. Note that synchronous requests may temporarily
lock the browser, disabling any actions while the request is active.
You might want to try jQuery Deferreds like this:
var jqxhr = $.getJSON(url);
jqxhr.done(function(data) {
...
draw_polygon(data);
});
This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 4 years ago.
I try to get some info from external php with ajax and use the data but my global var return undefined.I try with async false but is deprecated.If i console in success function it has value outside is undefined.
var pkz;
$(function(){
$.ajax({
type:'GET',
url: '/user/cred',
success: function (data){
pkz=data;
}
});
console.log(pkz);
The problem with your code is that the execution is asyncronous. When you run console.log, the ajax did not finished. Put it inside the ajax callback.
The ajax do not block the execution. It continue without finished. You SHOULD use callbacks.
If you want to use ajax syncronous:
$.ajax({
type: "GET",
url: remote_url,
async: false
})
This is a horrible solution.
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 9 years ago.
I'm trying to send a few AJAX requests. It has to collect the data into a variable, and after it's done, it has to output the variable. If I don't do it synchronously, it will just output the variable before the requests are done. Is is possible to keep using the page, while the requests are running? The code could look something like this:
for (var i=0;i<10;i++) {
$.ajax({
type: "GET",
url: "http://google.com",
async: false,
data: "",
success:function(data){
total += $(data);
alert(total);
}
}
That should load http://google.com/ 10 times, and output data into a variable called total. It is not my code I use (I like to keep it as private as possible), but only an example.
While it's loading Google 10 times, the page pauses because of async: false. Is is possible to make the page still work, and basically do the AJAX in the background? While it's loading, I can't do anything on the page.
If I don't do it synchronously, it will just output the variable before the requests are done.
No, it will output the variable 10 times after each request is done. To avoid that, use counter for how many requests have finished:
for (var i=0;i<10;i++) {
$.ajax({
type: "GET",
url: "http://google.com",
async: true,
data: "",
success:function(data){
total += $(data);
if (!--i)
alert(total);
}
}
}