This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 8 years ago.
I've got AJAX which gets timezone information in a function and I want it to return the result.
I now understand that AJAX is asynchronous so I need to have a callback function. I've looked at examples but I can't wrap my head around it.... I'm not sure where the arguments in my getTimezone() function go if I change that to just take a callback function.
Any help would be appreciated, here's the code:
ztimezone=getTimezone(lat,lng);
function getTimezone( tlat, tlong) {
url = "https://maps.googleapis.com/maps/api/timezone/json?location="+tlat+","+tlong+"×tamp=1331161200&key=******";
$.ajax({
url: url,
type: "GET",
crossDomain: true,
dataType: 'json',
success: function (data) {
alert(data.timeZoneId);
zdata=((data.rawOffset/60)/60);
},
error: function (xhr, err) {
alert(xhr.responseText);
}
});
return zdata;
}
function getTimezone(tlat, tlong, callback) { // <----- HERE
var url = "https://maps.googleapis.com/maps/api/timezone/json?location="+tlat+","+tlong+"×tamp=1331161200&key=******";
$.ajax({
url: url,
type: "GET",
crossDomain: true,
dataType: 'json',
success: function(data) {
alert(data.timeZoneId);
var zdata = ((data.rawOffset/60)/60);
callback(zdata); // <----- HERE
},
error: function (xhr, err) {
alert(xhr.responseText);
}
});
// return zdata; // <----- HERE
}
The first line allows you to pass a callback into your function.
The one in the middle calls the callback with the result.
The last one is commented out because you can never return a result from an asynchronous function - you must use a callback (or, equivalently, a promise).
To use it, you would do this:
getTimezone(45, 16, function(zoneData) {
alert(zoneData); // or whatever
});
Related
This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 7 years ago.
I have this code:
function aaa (){
var db_data;
$.ajax({
url: "http://localhost:8888/aaa/{{$article->id}}",
type: "GET",
async: true,
dataType: "json",
success: function(data) {
db_data = data;
console.log(db_data);
},
error: function (data) {
console.log(data);
console.log('GRESKA NEKA');
}
});
console.log(db_data);
};
but then I get at least line console.log(aaa) - > undefined...
Why? First console.log work ok but outside ajax I cant get db_data... WHy?
You are ordering a pizza, then trying to eat it before it is delivered! Ajax is an async call and the success gets called-back long after the last console.log executes.
You need to only use Async data in side the callbacks.
An alternative is to use the promise returned by Ajax so you code becomes a function that "promises to return the data":
// Return the Ajax promise
function aaa() {
return $.ajax({
url: "http://localhost:8888/aaa/{{$article->id}}",
type: "GET",
async: true,
dataType: "json",
});
}
// and use like this
aaa().then(function(data){
// Do something with the data
}).fail(function(data){
// Do something with the data when it fails
});
Promises make the functions reusable.
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 8 years ago.
Hello I have a problem storing my json in a global variable, what I want is to do first all my ajax request then store each of the returned data to a global variable, but it seems it's not working correctly? Can Any help me to my problem? Thanks. :)
var series;
function columnChart(container)
{
url = base_url+"/codeigniter/index.php/AssistanceMonitoringModule/assistanceMonitoring/getSeries";
$.ajax(
{
type: "GET",
url: url,
success: function(data){
series = data;
},
dataType: "json",
error: function (xhr, ajaxOptions, thrownError) {
alert("XHR:"+xhr.status+"Error:"+thrownError);
}
});
callColumnChart(container,series);
}
You are using the variable too soon. The Ajax request will not be completed when you call callColumnChart. Move it into the ajax callback.
$.ajax(
{
type: "GET",
url: url,
success: function(data){
series = data;
callColumnChart(container,series);
},
dataType: "json",
error: function (xhr, ajaxOptions, thrownError) {
alert("XHR:"+xhr.status+"Error:"+thrownError);
}
});
This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 7 years ago.
I have this javascript:
$ajax = $.ajax({
type: 'GET',
url: 'DBConnect.php',
data: '',
dataType: 'json',
success: function(data) {},
error:function (xhr, ajaxOptions, thrownError) {
dir(thrownError);
dir(xhr);
dir(ajaxOptions);
}
});
console.dir($ajax);
console.dir($ajax.responseJSON);
console.dir($ajax) shows it has a property named responseJSON, but when I try to access it with $ajax.responseJSON it returns undefined:
Well, of course it's undefined, because at the moment when you run console at last lines of your code, response hasn't yet came from the server.
$.ajax returns promise, which you can use to attach done() and fail() callbacks, where you can use all the properties that you see. And you have actually used callback error and success, and that's where you can run code and other functions that rely on data in the response.
You can use this trick to get the response out:
jQuery.when(
jQuery.getJSON('DBConnect.php')
).done( function(json) {
console.log(json);
});
It's late but hopefully will help others.
The response, is the "data", in success... so you can access to that writing data[0], data[1], inside the success.
For example:
success: function(data) {
alert(data[0]);
},
If you want this response, out of the success, you can set a variable outside, and try this:
success: function(data) {
myVar = data;
},
Hope, this help.
For those who don't really mind if it's synchronous, like I was, you can do this:
$('#submit').click(function (event) {
event.preventDefault();
var data = $.ajax({
type: 'POST',
url: '/form',
async: false,
dataType: "json",
data: $(form).serialize(),
success: function (data) {
return data;
},
error: function (xhr, type, exception) {
// Do your thing
}
});
if(data.status === 200)
{
$('#container').html(data.responseJSON.the_key_you_want);
}
});
It runs through the motions, waits for a response from the Ajax call and then processes it afterwards if the status == 200, and inside the error function if something triggered an error.
Edit the options to match your situation. Happy coding :)
This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 8 years ago.
When I call a function within a function it returns undefined. When the function is called by itself it returns the data I expect it to return.
The functions:
function companyNumbers(account_id) {
$.ajax({
type: "GET",
url: "http://example.com/api/api_client_relationships/" + account_id,
dataType: 'json',
success: function(data) {
for(var i=0;i<data.length;i++){
console.log(companyNames(data[i].company_id)); // returns undefined
}
}
});
}
function companyNames(id) {
$.ajax({
type: "GET",
url: "http://example.com/api/api_company_names/" + id,
dataType: 'text',
success: function(data) {
return data; // returns valid result when not called within another function
}
});
}
data[i].company_id is just a value parsed from the returned json response. It acts as the argument passed to the companyNames function.
You're trying to return a value from an asynchronous callback. return data inside the callback won't return data back to the caller of companyNames. Instead, pass in a callback to companyNames and return the data through that:
function companyNames(id, callback) {
$.ajax({
type: "GET",
url: "http://example.com/api/api_company_names/" + id,
dataType: 'text',
success: function(data) {
callback(data);
}
});
}
Then companyNumbers becomes:
function companyNumbers(account_id) {
$.ajax({
type: "GET",
url: "http://example.com/api/api_client_relationships/" + account_id,
dataType: 'json',
success: function(data) {
for(var i=0;i<data.length;i++){
companyNames(data[i].company_id, function(data) {
console.log(data);
});
}
}
});
}
Welcome to the world of ajax, you can't leave browser waiting for the return, as its async. Instead, you should use a callback function:
companyNames(data[i].company_id, function(info){console.log(info)});
function companyNames(id, call_back) {
success: function(data) {
call_back(data); // returns valid result when not called within another function
}
This is because function companyNames starts an asynchronous process. It returns immediately after starting the ajax call, and it's return value is undefined because the function itself doesn't specify a return value, just a function to call once the ajax call actually completes.
This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 9 years ago.
I would like to create a JavaScript function which returns the value of a jQuery AJAX call. I would like something like this.
function checkUserIdExists(userid){
return $.ajax({
url: 'theurl',
type: 'GET',
cache: false,
data: {
userid: userid
},
success: function(data){
return data;
}
});
}
I know I can do this by setting async to false but I would rather not.
You can't return data returned by an AJAX call unless you want to call it synchronously (and you don't – trust me). But what you can return is a promise of a data returned by an AJAX call and you can do it actually in a very elegant way.
(UPDATE:
Please note that currently jQuery Promises are not compatible with the Promises/A+ specification - more info in this answer.)
Basically you can return the return value of your $.ajax(...) call:
function checkUserIdExists(userid){
return $.ajax({
url: 'theurl',
type: 'GET',
cache: false,
data: {
userid: userid
}
});
}
and someone who calls your function can use it like this:
checkUserIdExists(userid).success(function (data) {
// do something with data
});
See this post of mine for a better explanation and demos if you are interested.
you can pass in a callback function:
function checkUserIdExists(userid, callback) {
$.ajax({
...
success: callback
});
}
checkUserIdExists(4, function(data) {
});
With jQuery 1.5, you can use the brand-new $.Deferred feature, which is meant for exactly this.
// Assign handlers immediately after making the request,
// and remember the jqxhr object for this request
var jqxhr = $.ajax({ url: "example.php" })
.success(function() { alert("success"); })
.error(function() { alert("error"); })
.complete(function() { alert("complete"); });
// perform other work here ...
// Set another completion function for the request above
jqxhr.complete(function(){ alert("second complete"); });
Source
As of jQuery 1.8, the "success", "error" and "complete" callback are deprecated. Instead you should be using "done", "fail" and "always".
So you could have:
function checkUserIdExists(userid, callback) {
return $.ajax({
url: 'theurl',
type: 'GET',
cache: false,
data: {
userid: userid
}
})
.done(callback)
.fail(function(jqXHR, textStatus, errorThrown) {
// Handle error
});
}
checkUserIdExists(2, function(data) {
console.log(data); // Do what you want with the data returned
});
This isn't how JavaScript asynchronous programming was really meant to be done. Instead, use a callback in your success function to call another function to use your data returned from the server.
Tim, the two scenarios are mutually exclusive; an asynchronous operation will not serve any purpose for, nor will it be able to retrieve returned data.
You should look at an event-enabled infrastructure for your ajax calls