Jquery AJAX callback not executing on success [duplicate] - javascript

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

Related

Callback in ajax request [duplicate]

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

Unable to read returned Javascript object from a different script file [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 7 years ago.
Hey guys I have two simple JavaScript page. One holds the function that returns the object. The other read the returned object.
Unfortunately I am unable to read the returned object.
main.js
var userObj = getUserInfo('2');
console.log(userObj); //undefined
console.log(userObj.name); //undefined
globals.js
function getUserInfo(mapID){
var jqxhr = $.ajax({
url: user_url,
type: "GET",
cache: true,
dataType: "json",
statusCode: {
404: function () {
handleError404("Error 404 at getUserInfo();")
},
500: function () {
handleError500("Error 500 at getUserInfo();")
},
},
success: function (data) {
console.log(data);
var obj = {
name: data.name,
age: data.age,
weight: data.weight
}
console.log(obj); //{name:"Kanye West", age:23, weight:"450lbs"}
return obj;
}
});
}
As you can see, If I was to output the object in the function itself, I see the result. But not if I call it from the main.js page.
Any help would be greatly appreciated!
You don't return anything from getUserInfo so you shouldn't expect anything from it.
You are only returning something in the success callback function. That is is run asynchronously. It doesn't return anything for getUserInfo.
If you want to make your ajax call a separate function you can make it return a promise from $.ajax instead of using a success callback.
function getUserInfo(mapID){
return $.ajax({
url: user_url,
type: "GET",
cache: true,
dataType: "json",
statusCode: {
404: function () {
handleError404("Error 404 at getUserInfo();")
},
500: function () {
handleError500("Error 500 at getUserInfo();")
},
}
});
}
then in main.js
var promise = getUserInfo('2');
promise.done(function(userObj) {
console.log(userObj);
console.log(userObj.name);
});
You are not returning anything.
The success callback function in the $.ajax() call is invoked asynchronously, meaning it is executed after the HTTP request is done.
Also, it is a different function than getUserInfo. At this point you are just returning a value for the success function.
I will suggest using another function that will process whatever you receive in the success call. SO in your successs call you get to add a line like handleObject(obj)
You need to pass as function argument a callback or a promise.
Reason is simple. You are calling an ajax call, which will be finished after your function will end it's call. That is why you need to add a callback/promise.
function getUserInfo(mapID, callback){
var jqxhr = $.ajax({
url: user_url,
type: "GET",
cache: true,
dataType: "json",
statusCode: {
404: function () {
handleError404("Error 404 at getUserInfo();")
},
500: function () {
handleError500("Error 500 at getUserInfo();")
},
},
success: function (data) {
console.log(data);
var obj = {
name: data.name,
age: data.age,
weight: data.weight
}
callback(obj);
}
});
}
In order to execute your function you simply call:
getUserInfo(manId, function(object){
console.log('AJAX results');
});

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

Ajax callbacks didn't return [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 9 years ago.
Im trying to create an ajax function to get some params of the DB each time, but when I call the ajax method it is not returning correctly, when I do it debug the value was ok, but the return result isn't works.
$(document).ready(function () {
function foo(mod){
var uri="some url";
$.ajax({
type: "GET",
url: uri,
}).done(function( data ) {
return data;
});
}
// alert to get the result is always printing undefined
alert(foo("param_1"));
});
foo can't return the result of the ajax call, because the ajax call is asynchronous. foo returns before the call completes. Moreover, the return in your done handler returns from the done handler, not foo.
You'll need to have foo accept a callback, and then call that:
$(document).ready(function () {
function foo(mod, callback){
var uri="some url";
$.ajax({
type: "GET",
url: uri,
}).done(function( data ) {
callback(data);
});
}
// alert to get the result is always printing undefined
foo("param_1", function( data ) {
alert(data);
});
});
Or if you're really do no processing on it at all before giving it to the callback, you could supply callback to done directly:
$(document).ready(function () {
function foo(mod, callback){
var uri="some url";
$.ajax({
type: "GET",
url: uri,
}).done(callback);
}
// alert to get the result is always printing undefined
foo("param_1", function( data ) {
alert(data);
});
});
You can set async as false, but instead I recommend you to implement success and error handlers that can work async
$(document).ready(function() {
function foo(mod) {
var uri = "some url";
$.ajax({
type: "GET",
url: uri,
success: successHandler,
error: errorHandler
});
}
function successHandler(data, textStatus, xhr) {
// Handle your data here
console.log(data);
//alert(data);
}
function errorHandler(xhr, textStatus, errorThrown) {
// Magic
}
// alert to get the result is always printing undefined
//alert(foo("param_1"));
foo("param_1");
});

Categories

Resources