Callback in ajax request [duplicate] - javascript

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 6 years ago.
I have made API and trying use it in my jQuery scripts. But having problems with callbacks.
My JavaScript:
function findAll() {
var users;
$.ajax({
url: "/user",
type: "GET",
dataType: "json",
success: function (data) {
users = data;
}
});
return users;
}
Help me return received data, please.
Thanks in advance.

This will not work because you are returning users synchronously. The value will be undefined.
What is happening is this:
- var users is declared and set to undefined by the Javascript engine
the AJAX callback is registered to be called when the XHR request resolves
var users (now = undefined) is returned
users is assigned the response of the XHR request. But alas! It's too late and undefined has already been returned!!
This should work:
function returnUsers(users) {
return users;
}
var users = findAll(returnUsers);
function findAll(callback) {
$.ajax({
url: "/user",
type: "GET",
dataType: "json",
success: callback
});
}

Related

How to access data from a function that return an ajax get json response? [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 4 years ago.
I have a function that return json data using ajax:
function validateTagRequest(fileName) {
$.ajax({
type: "GET",
dataType: "json",
url: "/tags/find-tag/"+fileName.tag,
success: function(data){
console.log(data);
return data;
}
});
};
console.log(data) show exactly what I need.
But then I call the function:
var response = validateTagRequest(fileName);
useResponse(response); // this don't work, response = undefined
console.log(response);
console.log(response) return undefined
How can I handle the asynchronous of js to execute this code in order?
try a callback
function validateTagRequest(fileName, cb) {
$.ajax({
type: "GET",
dataType: "json",
url: "/tags/find-tag/"+fileName.tag,
success: function(data){
console.log(data);
cb(data);
}
});
}
validateTagRequest(fileName, function(response){
useResponse(response);
console.log(response);
});

Jquery AJAX callback not executing on success [duplicate]

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');
}
}
});
}

Make a function return false based on the AJAX response [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 function that I calling from within another function
function CheckForSession() {
var str="chksession=true";
jQuery.ajax({
type: "POST",
url: "chk_session.php",
data: str,
cache: false,
success: function(res){
if(res == "0") {
alert('Your session has been expired!');
}
}
});
}
How can I make the entire function CheckForSession return false if the response equals 0?
P.S. In my application, the response to this function can only be either 1 or 0.
You can't do this because of asynchronous nature of AJAX requests.
The best solution for you is to use promises:
function CheckForSession() {
var str="chksession=true";
return jQuery.ajax({
type: "POST",
url: "chk_session.php",
data: str,
cache: false,
success: function(res){
blabla = res;
if(res == "0") {
alert('Your session has been expired!');
}
}
});
}
CheckForSession().then(function(data) {
// successful
}, function() {
// error
})
jQuery.ajax by default returns promise object, and i is resolved when ajax request will finished. Then you can write your actions depending on the result
http://api.jquery.com/jquery.ajax/

JavaScript running without waiting for AJAX request to finish [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 small problem, I want to check if a user is logged in via AJAX POST to a PHP and then run the rest of the function, unfortunately the rest of the function is being ran without waiting for the AJAX to finish.. so that's bad news
function checkLogin() {
dat = 'chl=1&x='+Math.random();
$.ajax({
url: "/action.php",
type: "POST",
data: dat,
success: function(data) {
if (data)
return data;
return 0;
},
error: function(data) {
console.log('err'+data);
return;
}
});
}
function anotherFunction() {
logged = checkLogin(); // is the user logged in?
if (logged) {
// do other stuff
console.log('Logged in');
} else {
console.log('Not logged in..');
}
}
So this is my problem, it says logged is undefined.. Is there any solution to this, besides using setTimeout, something more "natural" in terms of time of wait?
AJAX is asynchronous--do it in the success: code.
Make it a synchronous request by adding asynch parameter and set it to false [not recommneded]
$.ajax({
url: "/action.php",
type: "POST",
data: dat,
asynch: false,
success: function(data) {
if (data)
return data;
return 0;
},
error: function(data) {
console.log('err'+data);
return;
}
[Recommended] call your desired method in success call back of Ajax call
$.ajax({
url: "/action.php",
type: "POST",
data: dat,
success: function(data) {
if (data)
return data;
yourDesiredFunctionHere();
return 0;
},
error: function(data) {
console.log('err'+data);
return;
}

JSON AJAX - Return empty object [duplicate]

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. ;)

Categories

Resources