Return javascript array not working [duplicate] - javascript

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 9 years ago.
I have a javascript functions that fetches some JSON from a PHP. When I get the JSON my plan is to parse it and load it in to an array and then return that array so that I can use the data anywhere.
This is the ajax function:
function get_ajax(route_val){
$.ajax({
url: "ajax.php",
dataType: 'json',
data: {
route: route_val
},
success: function(result) {
if(result.error == true){
alert(result.message);
}else{
$.each(result, function(key1, value1){
//console.log(key1 + ":" + value1);
returnarray[key1] = value1;
});
return returnarray;
}
}
});
}
</script>
If I then try to define say var arr = get_ajax('1'), arr is going to be empty. I can alert and console.log stuff from the array from inside the function but returning it returns nothing.
It does not seem to exist outside of the function.
Any ideas?

You are using Ajax incorrectly, the idea is not to have it return anything, but instead hand off the data to something called a callback function, which handles the data.
IE:
function handleData( responseData ) {
// do what you want with the data
console.log(responseData);
}
$.ajax({
url: "hi.php",
...
success: function ( data, status, XHR ) {
handleData(data);
}
});
returning anything in the submit handler will not do anything, you must instead either hand off the data, or do what you want with it directly inside the success function.

The problem is that your success function isn't returning your array to anywhere. What you need to do is fully handle your data right there inside of the success handler, or else call another method/function to do what's needed.
Hypothetically it might look something like this:
success: function(result) {
if(result.error == true){
alert(result.message);
}else{
$.each(result, function(key1, value1){
returnarray[key1] = value1;
});
//Something like this
ajaxHandlers.handleReturnedArray(returnarray);
}
}

If you absolutely want to have it return something, you can do a synchronous request (Despite it's not the point of AJAX (asynchronous JavaScript and XML)).
function get_ajax(route_val){
var returnarray = [];
$.ajax({
url: "ajax.php",
dataType: 'json',
async: false,
data: {
route: route_val
},
success: function(result) {
if(result.error == true){
alert(result.message);
}else{
$.each(result, function(key1, value1){
returnarray[key1] = value1;
});
}
}
});
return returnarray;
}

Related

Jquery Ajax Call Return

I have made a function which is the one below that i pass data to and returns the result as is. I made this way because i will be needing a lot of ajax call and i just made a function that i pass the data to and get the result as is and work with the result.
function FunctionsCall(data){
var ret;
$.ajax({
type:'GET',
url: 'includes/helpers/functions.php',
dataType:"json",
data: data,
success: function(result){
ret = result;
}});
return ret;}
Now i am calling it where i need it:
$('#register-name, #register-surname').keyup(function(e) {
var x = FunctionsCall({query: $(this).val(), funcid: 1});
(x!==1) ? $(this).addClass('input-has-error') : $(this).removeClass('input-has-error'); });
But strange is that i always see x as undefined. Pointing out the ret is filled with either 1 or 0 i don't know why it is not being passed to x.
Can you please help me out? It might be simple but i just experiment when needed with javascript and jquery.
Regards
ret doesn't get set until the success function runs, which is when the ajax finishes. FunctionCall returns straight away however. You'll either need to return the ajax deferred object or put your addClass/removeClass functionality in your success function.
A way to add your addClass/removeClass functionality to your success function would be like this:
function FunctionsCall(data, successFn) {
$.ajax({
type: 'GET',
url: 'includes/helpers/functions.php',
dataType: "json",
data: data,
success: successFn
});
}
$('#register-name, #register-surname').keyup(function(e) {
var element = $(this);
var data = { query: element.val(), funcid: 1 };
var successFn = function(x) {
if (x !== 1) {
element.addClass('input-has-error')
} else {
element.removeClass('input-has-error');
}
}
FunctionsCall(data, successFn);
});
The problem is that the ajax call takes time to execute, whereas your processing of x is immediately after the call to FunctionsCall
Imagine that in order to go to the php file and get the result, the browser has to send a request over the wire, the server needs to process the request and return the value, again over the wire. This process takes an unpredictable amount of time as it relies on network connections and server specs / current load.
The code to call the function and process the result happens immediately after this step and as such won't have the required values when it is run (browsers are much quicker at executing the next step than networks are at processing requests).
The best thing to do is to wrap your processing code up in it's own function, so it isn't immediately called, then call that function with the result once you get it. Like this:
// function defined, won't be called until you say so
var processMe = function(result) {
alert(result);
}
$.ajax({
// ajax params
success: function(result) {
// function called within success - when we know the request is fully
// processed, however long it takes
processMe(result));
}
});
You could also do the processing directly in the success block but the advantage of using a function is it's there to re-use in the future, plus, you also get to give it a nice understandable name, like outputValidatedMessage.
you must send ajax request syncronous
function FunctionsCall(data){
var ret;
$.ajax({
type:'GET',
async: false,
url: 'includes/helpers/functions.php',
dataType:"json",
data: data,
success: function(result){
ret = result;
}
});
return ret;
}
Ajax calls are asynchronous.
This means that while you call $.ajax(), the function continues to run and return x which is undefined, as the ajax response has not been send yet.
function FunctionsCall(data){
var ret;
$.ajax({
type:'GET',
async: false,
url: 'includes/helpers/functions.php',
dataType:"json",
data: data,
success: function(result){
ret = result;
}
});
return ret;
}
The below should work for you
function FunctionsCall(data){
var ret;
$.ajax({
type:'GET',
url: 'includes/helpers/functions.php',
dataType:"json",
data: data,
success: function(result){
(result !==1 ) ? $(this).addClass('input-has-error') : $(this).removeClass('input-has-error'); });
}});
}
maybe is because the ajax function is called asynchronously so the line var x= .... doesn't wait for the asignment and thats why is undefined. for that you should use a promise here is an example http://joseoncode.com/2011/09/26/a-walkthrough-jquery-deferred-and-promise/
http://www.htmlgoodies.com/beyond/javascript/making-promises-with-jquery-deferred.html
check if the following works, may be your GET method is taking time to execute.
var x;
function FunctionsCall(data){
var ret;
$.ajax({
type:'GET',
url: 'includes/helpers/functions.php',
dataType:"json",
data: data,
success: function(result){
ret = result;
x= result;
alert(x)
}});
return ret;}
if the snippet works, you should make you synchronous async: false or make callback function
try this code.
function FunctionsCall(data,callback) {
try {
ajax({
type: 'GET',
url: 'includes/helpers/functions.php',
dataType: "json",
data: data,
success: function (result) {
callback(result);
}
});
} catch(e) {
alert(e.description);
}
}
$('#register-name, #register-surname').keyup(function (e) {
var data = {
uery: $(this).val(),
funcid: 1
};
FunctionsCall(JSON.stringify(data), function (result) {
(result !== 1) ? $(this).addClass('input-has-error') : $(this).removeClass('input-has-error');
});
});

AJAX response into an 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 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);
});

javascript variable is not showing correct value [duplicate]

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...
}
}

scope of var in jquery function? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
What does Asynchronous means in Ajax?
why my var "temp" is 0 after the ajax?
function calc7() {
var temp = 0;
$.ajax({
type: "POST",
url: 'Helpers/CalcResult7.ashx',
data: { GU_ID: '<%=Request.QueryString["GUID"] %>' },
success: function (data) {
list1 = eval(data);
temp = parseFloat(myJSONObject.bindings[0].value);
$("#<%=ProResult7.GetSpanId %>").text(addCommas(temp));
}
});
return temp;
}
Because the ajax call is asynchronous, so temp is returned before being updated ...
Because the success function doesn't run until the HTTP response is comes back from the server.
Ajax is asynchronous.
Do what you want to do with the data in the success function (or in functions you call from it).
Don't try to wait for a response and then return data to a calling function.
Ajax calls are asynchronous but you can use CommonJS Promises/A pattern to achieve what you want. jQuery provides it's own implementation of it: jQuery.Deferred().
As others have mentioned here, because ajax is asynchronous, you're not guaranteed to get the updated temp variable before your return statement. It would be best to work within your success function. However, if you absolutely have to wait for that call to finish and return the temp variable, you can make it Non-asynchronous by adding async: false
function calc7() {
var temp = 0;
$.ajax({
type: "POST",
url: 'Helpers/CalcResult7.ashx',
data: { GU_ID: '<%=Request.QueryString["GUID"] %>' },
async: false,
success: function (data) {
list1 = eval(data);
temp = parseFloat(myJSONObject.bindings[0].value);
$("#<%=ProResult7.GetSpanId %>").text(addCommas(temp));
}
});
return temp;
}
S.ajax/$.post/$.get etc etc, all these are asynchronous process (which means, you will come out of the loop even before $.ajax is completed, even though it will be going to server side after coming out of the loop)
function calc7() {
var temp = 0;
$.ajax({
type: "POST",
.............
..............
}
});
return temp;
}
So just after the loop if you will check, the following statement might not have executed(depending upon the data set).
temp = parseFloat(myJSONObject.bindings[0].value);
so to check the data in temp variable you should put a debugger/alert inside $.ajax. example :
function calc7() {
var temp = 0;
$.ajax({
type: "POST",
url: 'Helpers/CalcResult7.ashx',
data: { GU_ID: '<%=Request.QueryString["GUID"] %>' },
success: function (data) {
list1 = eval(data);
temp = parseFloat(myJSONObject.bindings[0].value);
alert(temp);
$("#<%=ProResult7.GetSpanId %>").text(addCommas(temp));
}
});
return temp;
}
now you will get the value of temp

How to return value when AJAX request is succeeded [duplicate]

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

Categories

Resources