How to define variable before ajax call [duplicate] - javascript

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.

Related

Can't get AJAX call returned data [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 4 years ago.
I can't get the returned data of an GET AJAX call.
The call gets the data properly but I can't get the data I need in a variable and return it.
I know that the AJAX calls are asynchronous and I've tried different approaches but failed.
function getQuantity(Id) {
var productQuantity = null;
$.ajax({
type: "GET",
dataType: "json",
url: "/Product/ProductData/" + Id,
success: function (response) {
productQuantity = response.QuantityInStock;
console.log("in call: ", productQuantity);
}
});
console.log("in return: ", productQuantity);
return productQuantity;
}
This is what I get in the console:
in return: null
in call: 2724 -> this is the right value
Hope you can help.
You need to return the AJAX call and add asycn: false option
function getQuantity(Id) {
var productQuantity = null;
return $.ajax({
type: "GET",
dataType: "json",
async: false,
url: "/Product/ProductData/" + Id,
success: function (response) {
console.log("response: ", response);
}
}).responseText;
}

How to structure my AJAX to accept a callback function [duplicate]

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+"&timestamp=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+"&timestamp=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
});

Save the result if a jQuery AJAX call to a variable [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 8 years ago.
I have a PHP script that takes a query string returns and JSON object. I am trying to make an AJAX call that will return this JSON object so I can use it in jQuery autocomplete. Here is my AJAX call so far
$(document).ready(function(){
$("#searchBox").keyup(function(){
var search_result = $.ajax({
url:"/mm5/service/product_lookup_json.php",
type: "GET",
dataType: "json",
jsonp: false,
data: "query=" + $("#searchBox").val(),
success: function(data){
return data;
}
});
console.log(search_result);
});
});
This sends the result of the AJAX call to the console ( a javascript object). I can see a JSON in that object. I would think all I have to do to access the data I want is this
console.log(search_result.responseJSON);
But this just gives me undefined. What am I doing wrong here?
That is not the way to do it because it is an async call so the data will not be returned by the ajax call. Try this
$(document).ready(function(){
var search_result;
$("#searchBox").keyup(function(){
$.ajax({
url:"/mm5/service/product_lookup_json.php",
type: "GET",
dataType: "json",
jsonp: false,
data: "query=" + $("#searchBox").val(),
success: function(data){
search_result = data;
console.log(search_result);
}
});
});
});
You need to wait for the AJAX call to complete in order to access the data it returns.
$(document).ready(function(){
$("#searchBox").keyup(function(){
$.ajax({
url:"/mm5/service/product_lookup_json.php",
type: "GET",
dataType: "json",
jsonp: false,
data: "query=" + $("#searchBox").val(),
success: function(data){
//data is available at this points
console.log(data);
}
});
});
});

How retrieve responseJSON property of a jquery $.ajax object [duplicate]

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 :)

JavaScript function that returns AJAX call data [duplicate]

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

Categories