This question already has answers here:
How to add callback to AJAX variable assignment
(4 answers)
Closed 8 years ago.
i have this ajax call function.
function saveData(ip)
{
$JQ.ajax({
type: "POST",
url: "all_actions.php",
data:
{
page_url:document.URL,
ip_address:ip
},
success: function(responce)
{
if(responce)
{
var newtoken;
newtoken=responce;
return newtoken;
}
}
});
}
Then i have another function
function getToken()
{
var ip=myip
var mytoken;
mytoken=saveData(ip);
alert(mytoken);
}
My token giving undefined in alert.Although if i alert newtoken variable in savedata response it gives correct value in alert box.why if i return that avlue it does not assigned to mytoken.
is it something time delay issue.??
Need your help...
You cannot return from an asynchronous call.
You have to consume the return data inside the success function. Whatever you are going to do with token, write that code inside the success handler.
success: function(responce)
{
if(responce)
{
var newtoken;
newtoken=responce;
// Global variable
sourceid = newtoken;
return newtoken; // This won't work
}
}
Also
function getToken()
{
var ip=myip
var mytoken;
mytoken=saveData(ip); // This won't return any data
alert(mytoken); // This won't give you anything useful
}
Hi friends This is solution that for i was looking.
function saveData(ip)
{
return $JQ.ajax({
type: "POST",
url: "all_actions.php",
data:
{
page_url:document.URL,
ip_address:ip
},
async: false,
}).responseText;
}
function getToken()
{
var ip=myip
var mytoken;
mytoken=saveData(ip);
return mytoken;
}
The first 'A' in AJAX is 'Asynchronous'. Your alert is running before the AJAX request has had a chance to complete. You need to handle whatever you wish to do with the response inside of the success: function() or .done() functions of jQuery:
success: function(responce)
{
if(responce)
{
var newtoken = responce;
// Work here with newtoken...
}
}
Related
I am working on the jquery to call a function to get the return value that I want to store for the variable email_number when I refresh on a page.
When I try this:
function get_emailno(emailid, mailfolder) {
$.ajax({
url: 'getemailnumber.php',
type: 'POST',
data : {
emailid: emailid,
mailfolder: mailfolder
},
success: function(data)
{
email_number = data;
}
});
return email_number;
}
I will get the return value as 6 as only when I use alert(email_number) after the email_number = data;, but I am unable to get the value outside of a function.
Here is the full code:
var email_number = '';
// check if page refreshed or reloaded
if (performance.navigation.type == 1) {
var hash = window.location.hash;
var mailfolder = hash.split('/')[0].replace('#', '');
var emailid = 'SUJmaWg4RTFRQkViS1RlUzV3K1NPdz09';
get_emailno(emailid, mailfolder);
}
function get_emailno(emailid, mailfolder) {
$.ajax({
url: 'getemailnumber.php',
type: 'POST',
data : {
emailid: emailid,
mailfolder: mailfolder
},
success: function(data)
{
email_number = data;
}
});
return email_number;
}
However, I have been researching and it stated that I would need to use callback via ajax but I have got no idea how to do this.
I have tried this and I still don't get a return value outside of the get_emailno function.
$.ajax({
url: 'getemailnumber.php',
type: 'POST',
async: true,
data : {
emailid: emailid,
mailfolder: mailfolder
},
success: function(data)
{
email_number = data;
}
});
I am getting frustrated as I am unable to find the solution so I need your help with this. What I am trying to do is I want to call on a get_emailno function to get the return value to store in the email_number variable.
Can you please show me an example how I could use a callback function on ajax to get the return value where I can be able to store the value in the email_number variable?
Thank you.
From the jquery documentation, the $.ajax() method returns a jqXHR object (this reads fully as jquery XMLHttpRequest object).
When you return data from the server in another function like this
function get_emailno(emailid, mailfolder) {
$.ajax({
// ajax settings
});
return email_number;
}
Note that $.ajax ({...}) call is asynchronous. Hence, the code within it doesn't necessarily execute before the last return statement. In other words, the $.ajax () call is deferred to execute at some time in the future, while the return statement executes immediately.
Consequently, jquery specifies that you handle (or respond to) the execution of ajax requests using callbacks and not return statements.
There are two ways you can define callbacks.
1. Define them within the jquery ajax request settings like this:
$.ajax({
// other ajax settings
success: function(data) {},
error: function() {},
complete: function() {},
});
2. Or chain the callbacks to the returned jqXHR object like this:
$.ajax({
// other ajax settings
}).done(function(data) {}).fail(function() {}).always(function() {});
The two methods are equivalent. success: is equivalent to done(), error: is equivalent to fail() and complete: is equivalent to always().
On when it is appropriate to use which function: use success: to handle the case where the returned data is what you expect; use error: if something went wrong during the request and finally use complete: when the request is finished (regardless of whether it was successful or not).
With this knowledge, you can better write your code to catch the data returned from the server at the right time.
var email_number = '';
// check if page refreshed or reloaded
if (performance.navigation.type == 1) {
var hash = window.location.hash;
var mailfolder = hash.split('/')[0].replace('#', '');
var emailid = 'SUJmaWg4RTFRQkViS1RlUzV3K1NPdz09';
get_emailno(emailid, mailfolder);
}
function get_emailno(emailid, mailfolder) {
$.ajax({
url: 'getemailnumber.php',
type: 'POST',
data : {
emailid: emailid,
mailfolder: mailfolder
},
success: function(data)
{
// sufficient to get returned data
email_number = data;
// use email_number here
alert(email_number); // alert it
console.log(email_number); // or log it
$('body').html(email_number); // or append to DOM
}
});
}
This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 7 years ago.
I have a PHP file returning data in required array format to my FlotChart, it's working.
Now I'm trying to get this result in my script using ajax, however I cannot see result on global variable, as described below:
myJS.js
var EcomDashboard = function() {
return {
init: function() {
var dataEarnings = NULL;
$.ajax({
url:"operation.php",
dataType: "text",
success:function(data) {
alert(data); //show my array [ [1, 20],[2,30],[3,14] ]
dataEarnings = data;
}
});
alert(dataEarnings); //showing "NULL" but I need [ [1, 20],[2,30],[3,14] ]
...
What is the correct way to assign to my variable date Earnings the array [[1, 20], [2.30], [3.14]]?
Javascript is an async language, it means it won't wait the http request to finish to execute the next line. you will have to assign the variable inside the success block.
the alert shows null is becauseit got executed before the $.ajax http request line finishes.
may be you can do this using a callback:
dataAccess.js
var ecomDashboard = function() {
init: function(callback) {
var dataEarnings = NULL;
$.ajax({
url:"operation.php",
dataType: "text",
success:function(data) {
callback(data);
}
});
}
}
controller.js
ecomDashboard.init(function(data){
// data contains the array result
// do your stuff
})
event better:
since jquery 1.5 there is incorporated promise interface, and .success is going to be deprecated. edited: thanks to Kevin B
so with promise:
dataAccess.js
var ecomDashboard = function() {
init: function(callback) {
var dataEarnings = NULL;
return $.ajax({
url:"operation.php",
dataType: "text"
});
}
}
controller.js
ecomDashboard.init().done(function(data){
//do your stuff
alert(data);
}).fail(function(error){
//do stuff when error
});
$.ajax({
url:"operation.php",
dataType: "text",
success:function(data) {
doSomthingOnComplete(data);
}
});
function doSomthingOnComplete(data)
{
// do here your work
}
This is occurring because that alert(dataEarnings) is executing before your ajax request resolves. The first letter in the AJAX acronym is Asynchronous. So, ultimately your data is being set properly you are just trying to access it before the asynchronous call completes.
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 stringified array of objects in a database that I'm retreiving with an $.ajax call. I'm trying to use a callback function to get that data into an array outside of my ajax function.
function getMap(){
return $.ajax({
url: "getMap.php",
type: "POST",
data: "",
dataType: 'JSON',
success: dataHandler
});
};
function dataHandler(data){
console.log(JSON.parse(data));
return JSON.parse(data);
}
var loadedMap = getMap();
console.log(loadedMap);
The console.log inside of the dataHandler function shows up in my Javascript console as a standard Array (clickable, can view all the data). The console.log at the very end shows up in the console as [object Object]. I can see the actual data inside of that object in a "responseJSON" field, but I can't seem to correctly get that into the loadedMap array.
What am I missing here?
Edit: I feel like my question is different from all of the answers to other questions. Mine seems to be more of a scope problem. A lot of the answers advocated the .done and .fail ways to handle AJAX.
var loadedMap = [];
function getMap(){
return $.ajax({
url: "getMap.php",
type: "POST",
dataType: 'JSON',
});
};
getMap().done(function(r) {
if (r) {
loadedMap = r;
} else {
console.log("No data");
}
}).fail(function(x) {
console.log("error");
});
console.log(loadedMap);
This code successfully gets the array where "loadedMap = r", but when you console.log the loadedMap on the outside, its undefined. How can we get the actual data to be outside the AJAX functions?
The function getMap does not return the response, it just calls dataHandler when the response arrives.
create a global variable and assign the vallue of the JSON.parse(data) to that variable. :
var myData;
function getMap(){
...
});
};
function dataHandler(data){
console.log(JSON.parse(data));
myData = JSON.parse(data);
}
getMap();
JQuery's AJAX returns a promise, so you can either go the callback route, as it looks like you were trying to do, or you can simplify it with promises:
function getMap(){
return $.ajax({
url: "getMap.php",
type: "POST",
data: "",
dataType: 'JSON',
success: dataHandler
});
};
getMap().then(function(data){
loadedMap = JSON.parse(data);
console.log(loadedMap);
});
My Class looks like
function classUser() {
var userName;
var firstName;
var lastName;
var sessionid;
}
classUser.prototype.set_user_name = function (user_name) {
this.userName = user_name;
}
classUser.prototype.set_first_name = function (first_name) {
this.firstName = first_name;
}
classUser.prototype.set_last_name = function (last_name) {
this.lastName = last_name;
}
classUser.prototype.get_curr_session = function () {
return this.sessionid;
}
classUser.prototype.save = function () {
$.ajax({
type: "POST",
url: "http://myapihost.com:8080/api/1.0/user/",
data: JSON.stringify(this),
dataType: "json",
success: function (apiResponse) {
var currSessionID = apiResponse.sessionId;
this.sessionid= currSessionID;
},
error: function (apiResponse) {
alert("error : " + apiResponse);
this.sessionid= "Error";
}
});
}
I call them as
var User = new classUser();
User.set_first_name(userFirstName);
User.set_last_name(response.last_name);
User.set_user_name(response.username);
User.save();
var currSessionID = User.get_curr_session();
Sometimes, get_curr_session is called before success: call.
Question :
I tried returning sessionid from success itself so that save() function does the job. That is not working. hence i split across 2 functions.
Can I do it in one call itself? if I have use 2 functions - how do i make sure that it works all the time.
I could actually put assigning the currSessionID within success, however that breaks class sanctity. I have seen other solution like using "done", not sure if that would help here.
=======================================
I modified the code as below
classUser.prototype.save = function (callback) {
$.ajax({
type: "POST",
url: "http://myapihost.com:8080/api/1.0/user/",
data: JSON.stringify(this),
dataType: "json",
success: function (apiResponse) {
var currSessionID = apiResponse.sessionId;
this.sessionid= currSessionID;
callback(null, currSessionID);
},
error: function (apiResponse) {
alert("error : " + apiResponse);
this.sessionid= "Error";
callback("error", null);
}
});
}
When I call
User.save(mycallback);
function mycallback(error, sessId){
if(error) {
console.log("Some error occurred. Check code");
return;// Something went wrong
} else {
console.log("Session : " + sessId);
}
}
Is this good now?
Thanks
Ajay
That's because the success and error function of the ajax request are executed asynchronously.
To make sure this doesn't happen, you should add a callback to your save function that is called after the success or error functions ran.
classUser.prototype.save = function (callback) {
$.ajax({
type: "POST",
url: "http://myapihost.com:8080/api/1.0/user/",
data: JSON.stringify(this),
dataType: "json",
success: function (apiResponse) {
var currSessionID = apiResponse.sessionId;
this.sessionid= currSessionID;
callback(null, currSessionID);
},
error: function (apiResponse) {
alert("error : " + apiResponse);
this.sessionid= "Error";
callback(apiResponse, null);
}
});
}
Then, when calling the save function, you can do something like this:
User.save(function(error, sessId) {
if(error) {
// Something went wrong
} else {
// Do whatever you need to do
}
});
You should note that this will also run asynchronously. So if you want to work with the session ID, don't do that after the User.save(...) call, but inside the function.
$.ajax() issues an asynchronous call to the url specified in the options object. See the jQuery documentation at http://api.jquery.com/jQuery.ajax/
success is a callback function that is invoked when the call is completed and all the response stream is read by the browser so basically in most of the cases the callback (updating the session id) will execute after you try to retrieve it.
I think what is happening here is that the default ajax call is async which means that the code var currSessionID = User.get_curr_session(); can execute before the success call completes.
You have a couple of options, you can try and update your code to be more async capable, using callbacks or other methods, or specify that you want your ajax call to be synchronous.
This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 9 years ago.
function ajaxRefresh(actionUrl) {
$.ajax({
url: actionUrl,
success: function() {
return true;
}});
return false;
}
The function anyway returns false even when a request is succeeded, becouse the request is asynchronous. How I can return true when request is succeeded?
You should set parameter async to false. Try this code:
function ajaxRefresh(actionUrl) {
var succeed = false;
$.ajax({
async: false,
url: actionUrl,
success: function() {
succeed = true;
}});
return succeed;
}
You can't return "true" until the ajax requests has not finished because it's asynchron as you mentioned. So the function is leaved before the ajax request has finished.
Solution 1
function ajaxRefresh(actionUrl, successCallback) {
$.ajax({
url: actionUrl,
success: successcallback
});
}
But there's a workaround: Just add a callback parameter to the function. This function will be executed when the request has finished.
Solution 2
You can return a jquery deferred.
function ajaxRefresh(actionUrl, successCallback) {
return $.ajax({
url: actionUrl
});
}
Now you can use the function like:
function otherFunction()
{
ajaxRefresh().success(function() {
//The ajax refresh succeeded!
}).error(function() {
//There was an error!
});
}
For more information about jquery deferreds look at http://www.erichynds.com/jquery/using-deferreds-in-jquery/.
You can refactor your code a little bit so that your success callback triggers the next operation that depends on the true/false result. For example, if you currently have something like:
function main() {
// some code
if (ajaxRefresh(url)) {
// do something
}
}
You would change that to something like:
function main() {
// some code
ajaxRefresh(url);
}
function doSomething(successFlag) {
if (successFlag) {
// do something
}
}
function ajaxRefresh(actionUrl) {
$.ajax({
url: actionUrl,
success: function() {
doSomething(true); // or false as appropriate
}});
}
You could also put the if test into the ajax callback function instead of in the doSomething() function. Up to you.
Or you can make a synchronous request, and figure out the ajaxRefresh() function's return value after the request is done. I would not recommend that for most purposes.
I am a relatively newbie at this, but here is a suggested work around I came up with which eliminates the need to set asynch to false or anything like that. Just set a hidden field value with the result of the ajax call, and instead of checking return value, check the value of the hidden field for true/false (or whatever you want to put in it).
Example:
function doSomething() {
$.ajax({
...blah blah
},
success: function(results) {
if(results === 'true') {
$('#hidField').val('true');
}
else {
$('#hidField').val('false');
}
}
});
Then somewhere else where it's required, this doSomething function is called, and instead of checking the result of the ajax call, look for the hidden field value:
doSomething();
var theResult = $('#hidField').val();
if (theResult == 'true') {
...do whatever...
}
Use call back functions
Callback Function Queues:-
The beforeSend, error, dataFilter, success and complete options all accept callback functions that are invoked at the appropriate times.
so, here
function ajaxRefresh(actionUrl) {
$.ajax({
url: actionUrl,
success: function() {
return true;
}
error:function(){
return false;
}
});
}
You can get more details here
http://api.jquery.com/jQuery.ajax/
function ajaxRefresh(actionUrl) {
bool isSucesss=false;
$.ajax({
url: actionUrl,
success: function() {
isSucesss=true;
},
error:function() {
isSucesss= false;
}
});
return isSucesss;
}