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;
}
Related
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 already read this article How do I return the response from an asynchronous call? However I couldn't come up with a solution.
I'm doing an ajax request
function getdata(url)
{
console.log('Started');
jQuery.ajax({
type: "GET",
url: "http://myserver.com/myscript.php",
dataType: "json",
error: function (xhr) {
console.log('Error',xhr.status);
},
success: function (response) {
console.log('Success',response);
}
});
}
And Console displays everything fine but when I say
var chinese = getdata();
to get the data. I keep getting:
Uncaught TypeError: Cannot read property 'length' of undefined error for this line
var text = chinese[Math.floor(Math.random()*chinese.length)];
Can anybody help me here?
The problem is that you are using an asynchronous method expecting a synchronous result.
Therefore you should use the code in the result of the asynchronous call like the following:
function getdata(url) {
console.log('Started');
jQuery.ajax({
type: 'GET',
url: url,
dataType: 'json',
error: function(xhr) {
console.log('Error', xhr.status);
},
success: function(chinese) {
var text = chinese[Math.floor(Math.random()*chinese.length)];
// Do something else with text
}
});
}
getData('http://myserver.com/myscript.php');
I hope it helps :)
The error you get is because of the asynchronous nature of the call. I suggest you to assign the value after you get the success response from the API like below.
var chinese = getdata();
Then the function getdata() will be like
function getdata(url)
{
console.log('Started');
jQuery.ajax({
type: "GET",
url: "http://myserver.com/myscript.php",
dataType: "json",
error: function (xhr) {
console.log('Error',xhr.status);
},
success: function (response) {
initChinese(response.data);
}
});
}
And create a function initChinese() like
var text;
function initChinese(chinese){
text = chinese[Math.floor(Math.random()*chinese.length)];
}
You can also declare the text variable in global scope and then assign the value to text variable inside the success function without having to create a new function initChinese.
The problem is your getdata function does not return anything. In your getdata function you're doing a ajax request, which is an asynchronous request. So the data you're requesting won't, and can't be returned with your getdata function.
But you will have the requested data in your success function:
function getdata(url)
{
console.log('Started');
jQuery.ajax({
type: "GET",
url: "http://myserver.com/myscript.php",
dataType: "json",
error: function (xhr) {
console.log('Error',xhr.status);
},
success: function (response) {
console.log('Success',response);
var text = response[Math.floor(Math.random()*response.length)];
}
});
}
As I'm not able to test your code, you've to debug the rest on your own. But the response variable will be most likely your "chinese" variable.
You could try using callbacks or you could look at Promises.
The idea with callbacks is that you pass a function that is run after the ajax request is finished. That callback can accept a parameter, in this case the response.
Using callbacks:
function getData(url, successCallback, errorCallback) {
console.log('Started');
jQuery.ajax({
type: "GET",
url: url,
dataType: "json",
error: function(xhr) {
errorCallback(xhr.status);
},
success: function(response) {
successCallback(response);
}
});
}
var chinese;
getData("http://myserver.com/myscript.php", function(response) {
chinese = response; // you can assign the response to the variable here.
}, function(statusCode) {
console.error(statusCode);
});
Using Promises (< IE11 doesn't support this):
function getData(url) {
return new Promise(function(resolve, reject) {
console.log('Started');
jQuery.ajax({
type: "GET",
url: url,
dataType: "json",
error: function(xhr) {
reject(xhr.status);
},
success: function(response) {
resolve(response);
}
});
});
}
var chinese;
getData("http://myserver.com/myscript.php").then(function(response) {
chinese = response;
console.log(chinese);
}, function(statusCode) {
console.error(statusCode);
});
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/
I have a difficulty to know when all Ajax requests are completed because I need this information to call another function.
Difficulty are to know when my 4/5 function with requests are completed. I use native function of ajax and none is working for me.
I used Chrome, and async requests.
Someone Helps me
I use this(not work):
$(document).ajaxStop(function() {
alert("Completed");
});
and this (not Work):
$(document).ajaxComplete(function() { alert("Completed"); });
Both ways I try use in another function thal calls all requests:
Example:
function Init()
{ Search("123"); Search2("1234"); Search3("12345");
... }
Extract one (of 5 requests,others are very similar ) of my request:
function Search(user) {
$.ajax({
url: 'www.example.com/' + user,
type: 'GET',
async: true,
dataType: 'JSONP',
success: function(response, textStatus, jqXHR) {
try {
if (response != null) {
alert("Have Data");
} else {
alert("are empty");
}
} catch (err) {
alert("error");
}
},
error: function() {
alert("error");
}
}); }
have you tried putting it in a done function? something like...
$.ajax({
url: 'www.example.com/' + user,
type: 'GET',
async: true,
dataType: 'JSONP'
}).done(function (data) {
code to execute when request is finished;
}).fail(function () {
code to do in event of failure
});
bouncing off what Michael Seltenreich said, his solution, if i understand where you guys are going with this...might look something like:
var count = 0;
function checkCount(){
if(count == 5 ){
//do this, or fire some other function
}
}
#request one
$.ajax({
url: 'www.example.com/' + user,
type: 'GET',
async: true,
dataType: 'JSONP',
}).done( function(data){
count += 1
checkCount()
})
#request two
$.ajax({
url: 'www.example.com/' + user,
type: 'GET',
async: true,
dataType: 'JSONP',
}).done( function(data){
count += 1
checkCount()
})
and do it with your five requests. If that works out for you please make sure to mark his question as the answer;)
You can create a custom trigger
$(document).trigger('ajaxDone')
and call it when ever you finished your ajax requests.
Then you can listen for it
$(document).on('ajaxDone', function () {
//Do something
})
If you want to keep track of multiple ajax calls you can set a function that counts how many "done" values were passed to it, and once all are finished, you can fire the event.
Place the call for this function in each of the 'success' and 'error' events of the ajax calls.
Update:
You can create a function like so
var completedRequests= 0
function countAjax() {
completedRequests+=1
if(completedRequests==whatEverNumberOfRequestsYouNeed) {
$(document).trigger('ajaxDone');
}
}
Call this function on every success and error events.
Then, ajaxDone event will be triggered only after a certain number of requests.
If you wanna track specific ajax requests you can add a variable to countAjax that checks which ajax completed.
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");
});