function json (url){
$.getJSON(url, function(data) {
return data;
})
}
this function don't see "data"
function MakeAlert(){
data = json('action.php');
window.alert(data.name);
}
this work:
function json (url){
$.getJSON(url, function(data) {
window.alert(data.name);
})
}
That's because the $.getJSON is asynchronous. It sends the request and returns immediately. Once the server responds (which might be a few seconds later) it invokes the success callback and that's why the data is accessible only inside this callback.
If you want to block the caller you could send a synchronous request (note that this might freeze the UI while the request is executing which defeats the whole purpose of AJAX):
function json(url) {
var result = null;
$.ajax({
url: url,
async: false,
dataType: 'json',
success: function(data) {
result = data;
}
});
return result;
}
function json (url){
$.getJSON(url, function(data) {
return data;
})
}
You cannot use return here. You would return data the to anonymous closure function.
Your best shot is to use a callback function which should be applied when the getJSON success handler is executed.
function json (url, cb){
$.getJSON(url, function(data) {
cb.apply(null, [data]);
})
}
usage
json('action.php', function(data){
alert(data);
});
Related
In the following code, I want the alerts to come in order (1st call followed by the second), but it keeps coming the other way around. This is causing some variables to become undefined. What is the order of execution when having multiple ajax queries in the same code? How can I change the order of the alerts?
$(document).ready(function () {
function get_det() {
$.ajax({
url: "aa.php",
type: "POST",
success: function (result) {
alert("1st call");
}
});
}
$.ajax({
type: "POST",
contentType: "application/json",
url: "dd.php",
success: function (result) {
initializeMap();
}
});
function initializeMap() {
//other code
calculateAndDisplayRoute();
//other code
function calculateAndDisplayRoute() {
//other code
get_det();
alert("2nd call");
//other code
}
}
});
Ajax is by default Asynchronous meaning there will be no wait for response.
That is why your 2nd call is calling before ajax request.
You can make ajax Syncronuous by setting async: false. Not recommended as it could cause browser hanging.
For Asynchronous process you can use callback function which only call when your request is completed.(Recommended)
In javascript you can do like this(For your code):
function get_det(callback) {//Your asynchronous request.
$.ajax({
url: "aa.php",
type: "POST",
success: function (result) {
alert("1st call");
callback();//invoke when get response
}
});
}
call like this:
get_det(secondFunction);//calling with callback function
function secondFunction()//your callback function
{
alert("2nd Call");
}
The difference in behavior is due to async nature of ajax calls. In your case, you want to perform some code once the call has executed, hence, you need to use callback functions.
Update your code to following
function get_det(callback) {
$.ajax({
url: "aa.php",
type: "POST",
success: function (result) {
alert("1st call");
if(callback) {
callback();
}
}
});
}
function calculateAndDisplayRoute() {
//other code
get_det(function() {
/* this is the place where you need to put code
* that needs to be executed after the ajax has been executed */
alert("2nd call");
});
}
I suggest chaining the promises that $.ajax returns.
$(document).ready(function () {
function get_det() {
return $.ajax({
url: "aa.php",
type: "POST"
}).then(function(result) {
// Do some stuff - you can even modify the result!
// Return the result to the next "then".
return result;
})
}
// Named after the php script you're hitting.
function dd() {
// Return the promise from Ajax so we can chain!
return $.ajax({
type: "POST",
contentType: "application/json",
url: "dd.php"
});
}
function initializeMap() {
// Do stuff before call
return get_det().then(function(getDetResult) {
// Do stuff after AJAX returns..
return {
getDetResult: getDetResult,
mapInitialized: true
};
});
}
// use it!
dd().then(function(result) {
alert('1st call');
// Pass result from dd to initializeMap.
return initializeMap(result);
}).then(function(initMapResult) {
alert('2nd call', initMapResult.mapInitialized);
});
});
I realize this is asked a lot and usually the answer is that AJAX is asynchronous and this is why it's returning undefined, but even though I set my async to false here, it's still returning undefined when the function is called. res is always undefined
function sendRequest(link, type, query) {
$(document).ready(function(){
$.ajax({
'url' : link,
'type' : type,
'data' : query,
'async' : false,
'dataType': "json",
'headers': {
'Cache-Control':'max-age=0',
'Accept':'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
'Content-Type':'application/x-www-form-urlencoded',
'Accept-Language':'en-US,en;q=0.8,ar;q=0.6',
},
'success': function(data) {
var res = data;
}
});
});
return res;
}
Also I am sure that the request is being sent correctly and that the response is received correctly as well
I think a better approach would be to have your sendRequest function return a jQuery Promise Object. As an example
function sendRequest(link, type, query) {
return $.ajax({
'url' : link,
'type' : type,
'data' : query,
'dataType': "json",
'headers': {
'Cache-Control':'max-age=0',
'Accept':'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
'Content-Type':'application/x-www-form-urlencoded',
'Accept-Language':'en-US,en;q=0.8,ar;q=0.6',
}
});
}
To use
sendRequest('/someurl', 'GET', {}).done(function(data) {
// do whatever you need with data here
});
You'll have to declare and assign res separately.
var res;
$.ajax({
// ...
'success': function (data) {
res = data;
}
});
return res;
Currently, res is being declared as a local variable solely inside the success callback. So, it won't be accessible to the rest of sendRequest().
Though, you should try to avoid using async: false with Ajax.
You can instead return the Deferred jqXHR provided by $.ajax(), allowing the calling function to add its own handler.
function sendRequest(link, type, query) {
return $.ajax({
// ...
});
}
sendRequest(...).done(function (data) {
// ...
});
More details and options are described in "How to return the response from an AJAX call?"
Firstly res should be outside ajax scope, and Secondly function will return before ajax call completes thats the reason its undefined:
$(document).ready(function(){
$.ajax({
'url' : link,
'type' : type,
'data' : query,
'async' : false,
'dataType': "json",
'headers': {
'Cache-Control':'max-age=0',
'Accept':'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
'Content-Type':'application/x-www-form-urlencoded',
'Accept-Language':'en-US,en;q=0.8,ar;q=0.6',
},
'success': function(data) {
MyFunction(data);
}
});
function MyFunction(data)
{
// do with ajax resonse what is needed
}
It's a scope problem.
You need to declare var res; in a scope that's accessible to the return, and just update that object inside of the AJAX.
function sendRequest(link, type, query) {
var res;
$(document).ready(function(){
$.ajax({
//...
'success': function(data) {
res = data;
}
});
});
return res;
}
AJAX is async (at least it should be, I would refrain from using async set to false), so the result will be undefined. Use a callback:
function sendRequest(link, type, query, callback) {
$.ajax({
..
..
'success': function(data) {
callback(data);
}
});
}
sendRequest(link, type, query, function(data) {
console.log(data); //YOUR DATA
});
I have a function in which I execute an ajax request and wait till I get a response and return a value but the value returned is undefined. What is wrong?
function GetVMData(url_s){
return $.ajax({
url: url_s,
crossDomain: true,
dataType: 'jsonp',
error: function(xhr, status, error) {
alert('failed')
}
}).pipe(function(data) { return data[4]; });
}
If I print the value of data[4] within the ajax callback it prints the right value, therefore i know the request is going through but when I try this:
var cord;
cord = GetVMData(url).done(function(cpu_USG) {
return cpu_USG;
});
alert(cord)
the value of cord is wrong.
var cord;
cord = GetVMData(url).done(function(cpu_USG) {
return cpu_USG;
});
alert(cord)
This code runs asynchronously. So you need to perform everything in the callback, like:
GetVMData(url).done(function(cpu_USG) {
alert(cpu_USG);
});
Here:
var cord;
cord = GetVMData(url).done(function(cpu_USG) {
return cpu_USG;
});
alert(cord);
cord contains object, not the value. And by the way, you don't know where ajax calling will be finished, so you should be familiar with idea of callbacks..
As an example:
function makeRequest(url, callback) {
$.ajax({
url: url,
crossDomain: true,
dataType: 'jsonp',
error: function(xhr, status, error) {
alert('failed')
},
success: callback
});
}
var do_something = function (data) {
alert(data[4]);
};
cord = makeRequest(url, do_something);
My function looks like that
var mail_ntfy=$("#nav_mail"), question_ntfy=$("#nav_question"), users_ntfy=$("#nav_users");
function CheckAll(){
var data=checkFor("m,q,u");
if(mail_ntfy.attr("data-number")!=data.m_count && data.m_count!=0)
mail_ntfy.attr("data-number", data.m_count);
if(question_ntfy.attr("data-number")!=data.q_count && data.q_count!=0)
question_ntfy.attr("data-number", data.q_count);
if(users_ntfy.attr("data-number")!=data.u_count && data.u_count!=0)
users_ntfy.attr("data-number", data.u-count);
showNotes(data.msg);
chngTitle(data.msg);
}
$(document).ready(function () {
setInterval(CheckAll(), 10000);
})
function checkFor(param){
$.ajax({
url: "core/notifications.php",
type: "POST",
dataType: "json",
data: {
chk:param
},
success: function (data) {
if(data.status!="error") {
console.log(data);
return data;
}
}
});
}
I got 2 questions:
1) I see that, checkFor function returns result (console.log shows result) but still getting data is undefined error message on line if(mail_ntfy.attr("data-number")!=data.m_count && data.m_count!=0). What am I missing?
2) I want to execute, CheckAll in every 10 seconds. But it doesn't start more than 1 time. why setinterval doesn't work properly?
checkFor() does not return any result. The console.log() statement is in the anonymous function attached to the success handler of your AJAX request; its return does not return from the checkFor() function.
If you want checkFor to return the data the AJAX call has to be synchronous. This is, however, bad Javascript practice (for example, it will hang the execution of scripts on the page until the request is complete). Unfortunately this whole design is flawed, but you could use this code if you REALLY have to:
function checkFor(param){
var result;
$.ajax({
url: "core/notifications.php",
type: "POST",
async: false,
dataType: "json",
data: {
chk:param
},
success: function (data) {
if(data.status!="error") {
console.log(data);
result = data;
}
}
});
return result;
}
You can't return data from success callback. Instead you can call CheckAll from success callback like this
success: function (data) {
if(data.status!="error") {
console.log(data);
//return data;
CheckAll(data);
}
}
To run checkFor instead every 10 seconds you can set the timer from within success callback too. That will call the checkFor 10 seconds after every successful ajax request. Using setInterval can end up with multiple simultaneous ajax calls.
success: function (data) {
if(data.status!="error") {
console.log(data);
//return data;
CheckAll(data);
setTimeout(checkFor,10000);
}
}
And your updated checkAll would be like
function CheckAll(data){
if(mail_ntfy.attr("data-number")!=data.m_count && data.m_count!=0)
mail_ntfy.attr("data-number", data.m_count);
if(question_ntfy.attr("data-number")!=data.q_count && data.q_count!=0)
question_ntfy.attr("data-number", data.q_count);
if(users_ntfy.attr("data-number")!=data.u_count && data.u_count!=0)
users_ntfy.attr("data-number", data.u-count);
showNotes(data.msg);
chngTitle(data.msg);
}
You are calling Ajax asynchronously therefore the system wont wait for ajax to end in order to continue proccessing. You'll have to add
async:false,
To your ajax call, like this:
function checkFor(param){
$.ajax({
url: "core/notifications.php",
type: "POST",
async:false,
dataType: "json",
data: {
chk:param
},
success: function (data) {
if(data.status!="error") {
console.log(data);
var ret=data;
}
}
});
return ret;
}
Hope it helps!
I use this helper function to receive JSON results for my requests:
function getData(url) {
$.get(url,
function(data) {
response = data;
return response;
}, 'application/json');
}
I give it some string as a part of url from my web application, like '/api/getusers', so it looks like getData('/api/getusers'). Now I need that string result containing JSON data that I receive from the url to be assigned to my variable, so it would look like this: var result = getData('/api/getusers'). Then I will process this JSON data. The problem is with the returning the response variable. It's undefined. Thanks!
try this
function getData(url) {
var data;
$.ajax({
async: false, //thats the trick
url: 'http://www.example.com',
dataType: 'json',
success: function(response){
data = response;
}
});
return data;
}
It's an asynchronous operation, meaning that function(data) { ... } runs later when the response from the server is available, long after you returned from getData(). Instead, kick off whatever you need from that function, for example:
function getData(url, callback) {
$.get(url, callback, 'application/json');
}
Then when you're calling it, pass in a function or reference to a function that uses the response, like this:
getData("myPage.php", function(data) {
alert("The data returned was: " + data);
});
Use $.ajax
$.ajax({
url: 'http://www.example.com',
dataType: 'json',
success: function(data){
alert(data.Id);
}
});