store result ajax into variable not working - javascript

I'm trying to store ajax result into variable. When I use console.log it gives my html tag that I wanted, But when I trying set into global variable it said undifined.
How I can store ajax result into global variable
var result;
$.ajax({
url: "person.html",
success: function(data){
//result=data;
console.log(data);
}
});
//console.log(result);

Ajax is asynchronous, meaning that the code to find out what result IS is running at the same time that the console log of result, which is why you're getting undefined, because result hasn't been set by the time the value is being console logged.
The only way I know of to console log the result would be to either do it within the ajax success function or to have the ajax success function call a subsequent function that contains the console log. It's the only way to be sure that a value has been returned before you console log it.
Examples:
EXAMPLE 1:
var result;
$.ajax({
url: "person.html",
success: function(data){
result=data;
console.log(result);
//Note that in this instance using the variable 'result' is redundant, as you could simply console.log data like you're already doing.
}
});
EXAMPLE 2:
var result;
$.ajax({
url: "person.html",
success: function(data){
result=data;
subsequentFunction(result);
}
});
function subsequentFunction(result){
console.log(result)
}
// Note that if you're doing something simple with result that this could be a bit long winded and unnecessary.
It all depends on how much you're wanting to do with the result as to which option would be better.
Note: There is also a property of an ajax call called 'async' that you can set to false which forces it to be synchronous, but this is generally considered a bad idea as it will prevent any other code from running until the result is returned and locking the browser.

$.ajax returns a promise, meaning that your code KNOWS it's going to receive a response, but because it's dependent on an external source, it doesn't know when this response will come in.
http://www.htmlgoodies.com/beyond/javascript/making-promises-with-jquery-deferred.html
See above link for more information on the subject.

ajax requests are async so your console.log(result) is running before getting response of your request. you should do something like this
var result;
$.ajax({
url: "person.html",
success: callback(data)
});
function callback (data){
result=data;
console.log(result);
}

You will not see anything beacuse the data is not populated yet. In your specific case you actually need to wait for the response. You can achieve it by using the following snippet.
$(document).ready(function(){
var data = $.parseJSON($.ajax({
url: 'person.html',
dataType: "json",
async: false
}).responseText);
var myProp = data.property; // Here you can access your data items
});
Another approach should be like you can push your data in an array and can access it in another function like this:
var result =[];
$(document).ready(function()
{
$.ajax({
url: 'person.html',
async:true,
dataType: "json",
success: function(data)
{
result.push(data);
}
});
});
NewFunction()
{
console.log(result);
}

Related

Error when storing JSON after an ajax request (jQuery)

I'm quite new to JavaScript/jQuery so please bear with. I have been trying to store the resulting JSON after an ajax request so I can use the login info from it later in my program. I get an error stating that "Data" is undefined. Here is the problematic code:
function LOGIN(){
$.ajax({
url: 'https://.......&JSONP=Data&.........',
success: function Success(){
var SessionData = Data();
(FunctionThatParsesJSON);
}
})
}
I have checked the URL manually and it works fine (including) being wrapped in the "Data" function. From what I have found online, this may be something to do with ajax been asynchronous. Can anyone suggest a way of storing the JSON so that I can use it later?
Try something like the following;
function LOGIN(){
$.ajax({
url: 'https://.......&JSONP=Data&.........',
success: function Success(data){
functionToProcessData(data)
})
}
When making your ajax call, you can handle the response given by assigning a parameter to the function. In the case above, I have passed the 'data' parameter to the success function allowing me to then use it in further functions (as demonstrated by 'functionToProcessData(data)'.
The response from ajax call is captured in success handler, in this case 'data'.
Check below code:
success: function(data){
var SessionData = data.VariableName;
// Here goes the remaining code.
}
})
Since people ask about explanation, thus putting few words:
When we do $.ajax, javascript does the async ajax call to the URL to fetch the data from server. We can provide callback function to the "success" property of the $.ajax. When your ajax request completed successfully, it will invoke registered success callback function. The first parameter to this function will be data came from server as response to your request.
success: function ( data ) {
console.log( data );
},
Hope this helps.
Internally everything uses promises. You can explore more on promises:
https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Promise
Apparently you are using JSONP, so your code should look like this:
$.ajax({
url: 'https://.......&JSONP=Data&.........',
dataType:"jsonp",
success: function (data){
(no need to parse data);
}
});
Another option:
$.ajax({
url: 'https://.......&JSONP=Data&.........',
dataType:"jsonp"
})
.done(function (data){
(no need to parse data);
});
See the documentation and examples for more details.
success: function (data, textStatus, jqXHR){
these are the arguments which get passed to the success function. data would be the json returned.

Javascript variable returns to original value after i overwrite it [duplicate]

I'm relatively new to JavaScript and I thought I knew how callback functions worked but after a couple of hours of searching the web I still do not understand why my code is not working.
I am making an AJAX request which returns a string array. I'm trying to set this array to a local variable, but it seems to lose it's value as soon as the callback function is executed.
var array;
$.ajax({
type: 'GET',
url: 'include/load_array.php',
dataType: 'json',
success: function(data){
array = data;
},
error: function(jqXHR, textStatus, errorThrown){
alert("Error loading the data");
}
});
console.debug(array);
In the console, array appears as undefined. Can anyone explain to me why this is not being set and how it is possible to set a local variable in a callback function.
The problem here is that console.log executes synchronously while the ajax call executes asynchronously. Hence it runs before the callback completes so it still sees array as undefined because success hasn't run yet. In order to make this work you need to delay the console.log call until after success completes.
$(document).ready(function() {
var array;
var runLog = function() {
console.log(array);
};
$.ajax({
type: 'GET',
url: 'include/load_array.php',
dataType: 'json',
success: function(data){
array = data;
runlog();
}});
});
The first A in ajax is for Asynchronous, which means that by the time you are debugging the array, the result still hasn't been delivered. Array is undefined at the point of displaying it's value. You need to do the console.debug below array = data.
The success function doesn't execute immediately, but only after the HTTP-response arrives. Therefore, array is still undefined at this point. If you want to perform operations on the HTTP-response data, do it from within the success function, or alternatively, define that operation inside of a function and then invoke that function from within the success callback.
Try calling a function to set this variable after your success:
var array;
var goodToProceed = function(myArr) {
console.debug(myArr);
};
$.ajax({
type: 'GET',
url: 'include/load_array.php',
dataType: 'json',
success: function(data){
goodToProceed(data);
},
error: function(jqXHR, textStatus, errorThrown){
alert("Error loading the data");
}
});
AJAX is asynchronous. You are setting the array variable, but not until after that debug executes. Making an AJAX call sends a request but then continues on in the code. At some later point, the request returns and your success or error functions execute.

Returning data from ajax results in strange object

I know this question hast probably been asked a thousand times, but i cannot seem to find the answer. I want result to be the data returned from the ajax-request, which should be a json-data array (the result of console.log(data)).
var result = $.ajax({
type: 'GET',
url: dataPath,
dataType: 'json',
success: function(data) {
console.log(data)
},
error: function(){
//alert("damn");
},
data: {},
aync: false
});
console.log(result);
However, console.log(result); will return some strange object, which I don't know how to handle. Why isn't result = data ?
Typo.
Change this:
aync: false
to:
async: false
And the ajax method still returns the jqXHR object doing the request, not the result. Use the data parameter in the success call and store it somewhere.
First of all remove the aync: false from your code. It should be spelled async: false but you don't need it to achieve your goal and what it actually does is block the entire browser's user interface resulting in a terrible user experience. Remember that "A" in AJAX means Asynchronous.
The result of an $.ajax() call is a promise which is not the same as your data, but it can still be useful to get to your data. You just need to use it in a certain way.
Try changing:
console.log(result);
to:
result.done(function (data) {
console.log(data);
});
or:
result.done(function (data) {
console.dir(data);
});
or even this might work - untested:
result.done(console.dir);
See this answer for a better explanation.
Initialize result inside success function.
var result;
$.ajax({
type: 'GET',
url: dataPath,
dataType: 'json',
success: function(data) {
result = data;
console.log(data)
},
error: function(){
//alert("damn");
},
data: {},
async: false
});
console.log(result);
There is a small spelling mistake aync: false should read async: false assuming of course that you require the request to run synchronously i.e. for the remainder of your code to wait for this result.
I think that the main issue here is that the result you are trying to output to the console is not being referenced by the ajax request.
It is entirely your choice how you reference the data returned by the ajax request, you chose the word data this could just as easily have been result or json_Data or return_Data or ....
Hence to send the result of the ajax request to the console I would suggest:
var result = $.ajax({
type: 'GET',
url: dataPath,
dataType: 'json',
success: function(result) {
console.log(result)
},
error: function(){
//alert("damn");
},
data: {},
async: false
});
You mentioned console.log(result) returns a strange object, actually this strange object is known as xhr (XMLHttpRequest) object.
Since the call is syncronous because of async: false so it's easy to get the returned data like
var result = $.ajax({...}); // get the xhr object in to result
console.log(result.responseText); // xhr object has a "responseText" property
As because result.responseText will be available only after the request completes and there is no chance to execute this console.log(result.responseText); because of async:false, before the request completes because a syncronous ajax request hangs on everything before it finish the request.
In your success callback data will be an object because of dataType: 'json' but outside of success callback, i.e. console.log(result.responseText); will be only text so to use it as an object you have to convert it to an object using $.parseJSON(result.responseText).

Setting local variable in a JavaScript callback function

I'm relatively new to JavaScript and I thought I knew how callback functions worked but after a couple of hours of searching the web I still do not understand why my code is not working.
I am making an AJAX request which returns a string array. I'm trying to set this array to a local variable, but it seems to lose it's value as soon as the callback function is executed.
var array;
$.ajax({
type: 'GET',
url: 'include/load_array.php',
dataType: 'json',
success: function(data){
array = data;
},
error: function(jqXHR, textStatus, errorThrown){
alert("Error loading the data");
}
});
console.debug(array);
In the console, array appears as undefined. Can anyone explain to me why this is not being set and how it is possible to set a local variable in a callback function.
The problem here is that console.log executes synchronously while the ajax call executes asynchronously. Hence it runs before the callback completes so it still sees array as undefined because success hasn't run yet. In order to make this work you need to delay the console.log call until after success completes.
$(document).ready(function() {
var array;
var runLog = function() {
console.log(array);
};
$.ajax({
type: 'GET',
url: 'include/load_array.php',
dataType: 'json',
success: function(data){
array = data;
runlog();
}});
});
The first A in ajax is for Asynchronous, which means that by the time you are debugging the array, the result still hasn't been delivered. Array is undefined at the point of displaying it's value. You need to do the console.debug below array = data.
The success function doesn't execute immediately, but only after the HTTP-response arrives. Therefore, array is still undefined at this point. If you want to perform operations on the HTTP-response data, do it from within the success function, or alternatively, define that operation inside of a function and then invoke that function from within the success callback.
Try calling a function to set this variable after your success:
var array;
var goodToProceed = function(myArr) {
console.debug(myArr);
};
$.ajax({
type: 'GET',
url: 'include/load_array.php',
dataType: 'json',
success: function(data){
goodToProceed(data);
},
error: function(jqXHR, textStatus, errorThrown){
alert("Error loading the data");
}
});
AJAX is asynchronous. You are setting the array variable, but not until after that debug executes. Making an AJAX call sends a request but then continues on in the code. At some later point, the request returns and your success or error functions execute.

Iterate on array, calling $.ajax for each element. Return array with all ajax results

I've just started working with JavaScript for non-trivial things, so this is probably straightforward...
What I'm trying to accomplish: iterate on an array of product references, fetch the JSON for each reference, and return an array of all the product information (with a hash-like structure indexed by reference).
What I've tried:
function fetchProductData(references){
var product_data = new Object();
references.forEach(function(ref){
$.ajax({
url: "http://localhost:3000/products/find.js?reference=" + ref,
dataType: "jsonp",
type: "GET",
processData: false,
contentType: "application/json",
success: function(data) {
product_data[ref] = data;
}
});
});
alert('before return: ' + product_data);
return product_data;
};
$(document).ready(function(){
var products = fetchProductData(references);
alert('products : ' + products);
});
Here's what I don't understand: the first time I call alert to display the array contents, the array is empty. However, on the second call, the array is populated with the data I want.
In other words, the "products :" alert displays the data I want in the code above. But if I comment the "before return: " alert, it no longer does. Why is this?
So my question is: how can I have jQuery make several $.ajax call to fetch product information, collect that information in an array, and return that array so I can use it elsewhere in my code?
Also, why is the data in the variable magically accessible after it is referenced in an alert?
The "A" in "AJAX" stands for "asynchronous" :). Your program doesn't wait for the call to complete before going on to the next iteration, meaning you'll probably not get all of your data. Also the alert has the same problem. Operation to concat 'before return:' to the string add just enough time to get some data in the variable. On a faster machine you might find you never get data.
I think you really need to rethink your approach. It's not a good idea to have multiple AJAX requests in a loop. It will greatly increase latency of the page. Pass all your parameters once using JSON, then have your server side script loop through that and return a single response in JSON.
function fetchProductData(references){
// make sure your "references" is a JSON object
$.getJSON('http://server/side/url', {'json':references}, function(product_data) {
// do something with product_data (alert them, put them in an array, etc)
});
}
function fetchProductData(references, cb){
var length = 0;
var product_data = new Object();
references.forEach(function(ref){
length++;
$.ajax({
url: "http://localhost:3000/products/find.js?reference=" + ref,
dataType: "jsonp",
type: "GET",
processData: false,
contentType: "application/json",
success: function(data) {
product_data[ref] = data;
if (++count === length) {
cb(product_data);
}
}
});
});
};
$(document).ready(function(){
var products = fetchProductData(references, function(products) {
alert('products : ' + products);
});
});
Use a callback on your asynchronous operation.
The reason it appears to work with the alert call is because alerting a message gives ajax enough time to populate your array. The return statement is only triggered after you click OK on the alert box giving your code a window of 250ms to populate the array with data.
You are executing you ajax query in async mode. And you want a sync result. Try to add:
async: false
Hope this helps.
your $.ajax call is asynchronous, so what is happening is that the first time you make the call, your javascript makes the call, moves on to the next line (alert) and then loops. You're data hasn't returned at that point yet. What you can do to remedy this is to set the async: false option in your $.ajax call.
This is an asynchronous operation. The only sure way to know when the data is ready is in the callback function: success: function () {...}, which gets called when the data has finally returned. Put your alert in there.

Categories