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 :)
Related
I'm trying to implement a function that after consulting a service brings the variables as global.
function ajax_test(str1, callback){
$.ajax({
url: '/path/service',
type: 'POST',
dataType: "json",
data: {'vars':$('form').serialize(), 'test':123},
success: function(data, status, xhr){
callback(data);
}
});
}
and I'm trying to call like this:
ajax_test("str", function(url) {
//do something with url
console.log(url);
});
Now, if I just call ajax_test() it returns an error, saying that callback is not a function.
How would be the best way to simply call the function and get the results to use global variables?
Edit:
I think a good question is: what is a good alternative to async: false? How is the best way to implement synchronous callback?
Edit 2:
For now, I'm using $.post() with $.ajaxSetup({async: false}); and it works how I expect. Still looking a way I could use with a callback.
Have to set the scope inside the success method. Adding the following should work.
function ajax_test(str1, callback){
$.ajax({
url: '/path/service',
type: 'POST',
dataType: "json",
data: {'vars':$('form').serialize(), 'test':123},
success: function(data, status, xhr){
this.callback(data);
}.bind(this)
});
}
As an argument of the ajax_test function, callback is in the scope of the ajax_test function definition and can be called anywhere there, particularly in the successcase. Note that calling ajax_test() without arguments will as expected make your code call a function that does not exist, named callback.
The following sends an Ajax request to the jsFiddle echo service (both examples of callback as anonymous or global function are given in the jsFiddle), and works properly :
function ajax_test(str1, callback){
$.ajax({
url: '/echo/json',
type: 'POST',
dataType: "json",
data: {
json: JSON.stringify({
'vars':$('form').serialize(),
'test':123
})
},
success: function(data, status, xhr){
callback(data);
}
});
}
ajax_test("unusedString", function(data){
console.log("Callback (echo from jsFiddle called), data :", data);
});
Can you check that the webservice you're calling returns successfully ? Here is the jsFiddle, I hope you can adapt it to your need :
https://jsfiddle.net/dyjjv3o0
UPDATE: similar code using an object
function ajax_test(str1) {
this.JSONFromAjax = null;
var self = this;
function callback(data) {
console.log("Hello, data :", data);
console.log("Hello, this :", this);
$("#callbackResultId").append("<p>Anonymous function : " + JSON.stringify(data) + "</p>");
this.JSONFromAjax = JSON.stringify(data);
}
$.ajax({
url: '/echo/json',
type: 'POST',
dataType: "json",
data: {
json: JSON.stringify({
'vars': $('form').serialize(),
'test': 123
})
},
success: function(data, status, xhr) {
console.log("Success ajax");
// 'self' is the object, force callback to use 'self' as 'this' internally.
// We cannot use 'this' directly here as it refers to the 'ajax' object provided by jQuery
callback.call(self, data);
}
});
}
var obj = new ajax_test("unusedString");
// Right after the creation, Ajax request did not complete
console.log("obj.JSONFromAjax", obj.JSONFromAjax);
setTimeout(function(){
// Ajax request completed, obj has been updated
console.log("obj.JSONFromAjax", obj.JSONFromAjax);
}, 2000)
You cannot expect the Ajax request to complete immediately (don't know how it behaves with async: false though, this is why you need to wait for a while before getting the actual response.
Updated jsFiddle here : http://jsfiddle.net/jjt39mg3
Hope this helps!
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.
I have this $.post peace of code:
$.post("../admin-login",
{
dataName:JSON.stringify({
username:uname,
password:pass,
})
}, function(data,status){
console.log("Data:"+data);
answer = data;
}
);
and I wont to transform it to $.ajax. On the servlet side I am demanding request.getParamter("dataName") but I do not know how to write data: section in $.ajax so that I can get parameters like that(request.getParamter("dataName"))? Also, it seems to be problem with this type of code, I am asuming cause of async, that I cannot do this:
var answer="";
function(data,status){
console.log("Data:"+data);
answer = data;
}
And that answer is keeping empty(""), even though in console is written in deed "true" or "false" as my server answers. What is this about?
Thanks in advance.
I found out that problem is in the click() event. Ajax finishes when click() finishes, so I am not able to get data before event is done. What is bad in that is that I cannot fetch data because it is finished. Does anyone know how to solve this?
$.post("../admin-login",
{
dataName:JSON.stringify({
username:uname,
password:pass,
})
}, function(data,status){
console.log("Data:"+data);
answer = data;
}
);
becomes
function getResult(data) {
// do something with data
// you can result = data here
return data;
}
$.ajax({
url: "../admin-login",
type: 'post',
contentType: "application/x-www-form-urlencoded",
data: {
dataName:JSON.stringify({
username:uname,
password:pass,
})
},
success: function (data, status) {
getResult(data);
console.log(data);
console.log(status);
},
error: function (xhr, desc, err) {
console.log(xhr);
}
});
You need to see how the information os arriving to your servlet as query parameter or payload.
See this HttpServletRequest get JSON POST data
You could try structuring your AJAX request like the below:
var dataName = username:uname, password:pass;
$.ajax({
url: "../admin-login",
data: JSON.stringify(dataName),
type: "POST",
cache: false,
dataType: "json"
}).done(function(data, status) {
console.log("Data:"+data);
answer = data;
});
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
});
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