This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 8 years ago.
I'm using an AJAX call in a function to retrieve some data from the server, in this way:
getPolicies: function() {
$.ajax({
async: false, // wait for response
type: "GET",
url: "http://localhost:8080/getPolicies",
contentType: "application/json",
dataType: "json",
success: function(jsonList) {
for(var i in jsonList) {
console.dir(jsonList[i].policyName);
}
return jsonList;
},
failure: function(err) {console.log("Error");}
});
}
I correctly get the JSON array:
[
{
"policyName": "policy1"
},
{
"policyName": "policy2"
},
{
"policyName": "policy3"
}
]
This JSON array is returned by the function.
But when I call the function getPolicies() I only get an empty JSON object {}. Specifically, if i try
var policies = getPolicies();
console.log(policies[1].policyName);
I get this:
Uncaught TypeError: Cannot read property 'policyName' of undefined
So, how is possible that even if I correctly get the JSON array, the function returns an empty object?!
Thanks...
Even though the AJAX request is synchronous *), the return statement still returns only from the success handler. Try something like this:
getPolicies: function() {
// Declare variable here
var resultList = null;
$.ajax({
async: false, // wait for response
type: "GET",
url: "http://localhost:8080/getPolicies",
contentType: "application/json",
dataType: "json",
success: function(jsonList) {
for(var i in jsonList) {
console.dir(jsonList[i].policyName);
}
// Set the variable in the scope of getPolicies.
resultList = jsonList;
},
failure: function(err) {console.log("Error");}
});
// This one actually returns getPolicies
return resultList;
}
But in general, it's regarded bad practice to make AJAX calls synchronous. Instead, you can better call the necessary functionality from the success handler. That can also be another function. For instance, you can declare
function processPolicies(policies)
{
console.log(policies[1].policyName);
}
And your call handler can look like this (:
$.ajax({
async: true, // just let it run,
type: "GET",
url: "http://localhost:8080/getPolicies",
contentType: "application/json",
dataType: "json",
success: function(jsonList) {
processPolicies(jsonList);
},
...
*) The first A even stands for Asynchronous. But on the other hand, the X stands for XML, so what you're doing here should actually be called JaJ rather than AJAX. ;)
Related
My code is something like this:
for (var i = 0; i < stf_file_names.length; i++) {
var temp_file_name = stf_file_names[i];
$.ajax({
type: "POST",
url: "php_scripts/some_script.php",
data: {
stf_file_name: temp_file_name
},
timeout: 600000,
success: function (response) {
console.log("SUCCESS : ", response);
//pausecomp(2000);
}
});
}
Here, some_script.php updates a database in the backend and echo's the primary key of the updated row, which is a number. But when I'm logging using the success function, I can see that it is logging only the primary key echoed by the last ajax call multiple times.
But if I use some kind of sleep function, which is pausecomp() in this case, it prints different the primary keys echoed.
I have looked at multiple stackoverflow questions regarding this and have not been to solve it.
async: false will do the job
$.ajax({
type: "POST",
async: false,
url: "php_scripts/some_script.php",
data:
However, this is not recommended, Better to make a loop by calling a function recursively from success.
Here is the example.
i=0;
function loop_stf_file_names(i){
var temp_file_name = stf_file_names[i];
$.ajax({
type: "POST",
url: "php_scripts/some_script.php",
async: false,
data: {
stf_file_name: temp_file_name
},
timeout: 600000,
success: function (response) {
console.log("SUCCESS : ", response);
if( i < stf_file_names.length ){
loop_stf_file_names( ++i );
}
}
});
}
$.ajax() is a async function.
By looping over ajax you are most probably sending the same data in all requests, due to which you are receiving same key for all requests.
Just sure , you send the next request when you have received the response from first request.
This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 5 years ago.
I'm sending a request to the server to check a user_id and session_id pair, to make sure that it's valid. This function gets the session data associated with the session_id, and then if the user_id from the session data matches the one passed to the function as an argument, it should execute the callback. Unfortunately, the callback doesn't execute for some reason.
If I type into the console "session_is_valid(2, 1, function() { alert('hi'); });", I can see "success" logged in the console, but no alert. Likewise, if I use an invalid pair, I correctly am notified with a "failure" message. But the callback never executes.
Is this some problem with how I'm using the console in my browser? Or is there a problem with my function?
//Confirm a session id / user id pair
function session_is_valid(session_id, user_id, callback) {
var data = {'id': session_id};
return $.ajax({
type: "POST",
url: ears_path + "?q=session",
data: JSON.stringify(data),
contentType: 'application/json; charset=UTF-8',
dataType: 'json',
success: function (result) {
if(result.user_id === user_id) {
console.log('success');
callback
}
else { console.log('failure'); }
}
});
}
There are some comments where you can see the same answer. In my opinion, you will need to make callback() instead of callback to call the function, if you just execute callback you are retrieving and fn object (function object), but you won't execute it. You can check the solution openning the browser console, and writting callback and callback(), if you hace the function in the global scope or if you are debugging the script.
This is how I perform mine, modify to suit your needs.
function run_some_ajax() {
ajax_call(function(result) { //by populating result here, you can reference the data returned from your ajax call
//success callback logic here
console.log(result);
});
}
function ajax_call(callback) {
$.ajax({
type: "POST",
url: ears_path + "?q=session",
data: JSON.stringify(data),
contentType: 'application/json; charset=UTF-8',
dataType: 'json',
success: function (result) {
if(result.user_id === user_id) {
console.log('success');
if(typeof callback === "function") { //always check to see if callback is in fact a function
callback(result); //place results into your callback function to reference later
}
} else {
console.log('failure');
}
}
});
}
I've got a small javascript function that's only purpose is to call a script to get some data from the database so it can be used by other functions on the client side.
I'm using a jQuery call to get the data but for me to pass the object out of the success functions scope I need to turn asynchronous off which raises a deprecation warning.
My function works as intended currently but I'd like to use a method that isn't deprecated. Here is my function:
function getData(ID) {
var Data = {};
$.ajax({
url: 'script',
method: 'POST',
dataType: 'json',
async: false,
data: {action: 'get', id: ID },
success: function(response) {
Data = response;
})
});
return Data;
}
I've changed the variable names for privacy reasons so apologies if they're vague.
Also why is synchronous calls considered harmful to the end users experience?
As AJAX call is asynchronous, you will always get blank object ({}) in response.
There are 2 approach.
You can do async:false
To get response returned in AJAX call try like below code. Which wait for response from server.
function getData(ID) {
return $.ajax({
url: 'script',
method: 'POST',
dataType: 'json',
//async: true, //default async call
data: {action: 'get', id: ID },
success: function(response) {
//Data = response;
})
});
}
$.when(getData(YOUR_ID)).done(function(response){
//access response data here
});
This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 7 years ago.
I have to make numerous AJAX calls and want to set up a simple method to handle this. I created the following
function testingAjax(url) {
$.ajax({
type: "GET",
contentType: "application/json; charset=utf-8",
url: url,
data: "{}",
dataType: "json",
success: function(data) {
//alert(data);
return data;
},
error: function(err) {
alert('error')
}
});
};
When I call testingAjax from another method, I get an Undefined error, yet when I alert from within testingAjax it is correct.
function testingCall(){
var data = testingAjax(url);
alert(data);
}
Basically, I want to return the data from the AJAX call, and parse it elsewhere. What am I doing wrong?
You'll want to add a callback param (which is a function) and pass it to success in place of what you already have.
function testingAjax(url, cb) {
$.ajax({
type: "GET",
contentType: "application/json; charset=utf-8",
url: url,
data: "{}",
dataType: "json",
success: cb,
error: function(err) {
alert('error')
}
});
};
To use it:
testingAjax('myurl', function(data) {
console.log(data);
});
This will take the value of the success callback and immediately pass it as an argument to your custom callback, which will allow you access to data.
This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Synchronous calls with jquery
I am trying to return a value from a function that contains an ajax call (please see code below).
The returnValue variable is undefined at the alert and when it returns. Can anyone help please?
function getLightboxImages(){
var returnValue;
jQuery.ajax({
url: "http://test.domain.com/WebService.svc/GetAllI",
data: { id: "2", hash:"MaD01" },
async: false,
dataType: "jsonp",
success: function (result) {
returnValue = result
}
});
alert(returnValue);
return returnValue;
}
The alert would have to be placed in the success function, as that is called when ajax returns. What you have above will send the request and then try to alert the returned value before the request is completed.
try this code, for JSONP you have to use callback function rather than success method.
$.ajax({
url: 'http://test.domain.com/WebService.svc/GetAllI',
type: 'GET',
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "jsonp",
jsonp: "callback",
jsonpCallback: "jsonpCallbackfunction",
error: function () {
alert("Error in Jsonp");
}
});
function jsonpCallbackfunction(responseData) {
alert(responseData);
}
http://cmsnsoftware.blogspot.com/2012/02/how-to-use-cross-domain-ajax-request.html#0
function getLightboxImages(){
var returnValue;
jQuery.ajax({
url: "http://test.domain.com/WebService.svc/GetAllI",
data: { id: "2", hash:"MaD01" },
async: false,
dataType: "jsonp",
success: function (result) {
returnValue = result
}
});
alert(JSON.stringify(returnValue));
return returnValue;
}
Cross-domain requests can only be async, as cross-domain requests rely on a dynamic script tag, which can never be synchronous and must use datatype json and the GET method.
For same domain requests, try stringifying json objects before alerting, like above!
You can't make synchronous JSONP requests.
Use a callback instead of return:
function getLightboxImages(callback) {
jQuery.ajax({
url: "http://test.domain.com/WebService.svc/GetAllI",
data: { id: "2", hash:"MaD01" },
dataType: "jsonp",
success: function (result) {
callback(result);
}
});
}
Usage:
getLightboxImages(function(result){
alert(result);
});