Displaying json returns undefined [duplicate] - javascript

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
I have a nested data structure / JSON, how can I access a specific value?
Basically I have a returned json object like this:
"products":[
{
"id": "21102165",
"name": "Eliza J (3/4 sleeve ruched waist dress)",
}]
My method to display it:
function getCart(){
var json = $.getJSON('https://'+storedomain+'/cart?'+fcc.session_get()+'&output=json&callback=?');
alert(json['name']);
}
However the alert displays "undefined". Where I'm I doing wrong here?
Thanks

$.getJSON return $.Deferred object and not a result
function getCart(){
$.getJSON('https://'+storedomain+'/cart?'+fcc.session_get()+'&output=json&callback=?', function(data) {
console.log(data.products[0].name);
});
}
you can do:
function getCart(){
return $.getJSON('https://'+storedomain+'/cart?'+fcc.session_get()+'&output=json&callback=?');
}
$.when(getCart()).then(function(data) {
console.log(data.products[0].name);
});

Use the success callback.
var jqxhr = $.getJSON("example.json", function(data, textStatus, jqXHR) {
alert("success");
})
.success(function(data, textStatus, jqXHR) { alert("second success"); })
.error(function() { alert("error"); })
.complete(function() { alert("complete"); });
See the API documentation for getJSON.

Your method should be:
function getCart(callback) {
var url = 'https://'+storedomain + '/cart?'+fcc.session_get()+'&output=json&callback=?';
$.getJSON(url, callback);
}
// Usage
getCart(function(data) {
console.log(data.products); // array of car objects
});
Or you can use deffered object as explained in salexch answer.
You should become familiar with asynchronous nature of AJAX requests and with callback functions.

Related

How to return data to variable after ajax call success [duplicate]

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.

Get resultfrom AJAX call into javascript variable [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 been trying to find a solution to this for a while now but i can not seem to get it to work.
What i am doing:
I am trying to get a array from my php file so i can use it in my javascript.
Example.php
$arr = Array(
Array(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0),
Array(1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0),
Array(0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0),
Array(0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,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0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,1,1,3,3,3,3,3,3,3,3),
Array(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,1,1,3,3,3,3,3,3,3,3,3),
Array(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,0,0,0,0,0,1,3,3,3,3,3,3,3,3,3,3),
Array(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,3,3,3,3,3,3,3,3,3,3)
);
echo json_encode($arr);
And i am calling this with a javascript function
function getArray(){
$.ajax({
url: 'Example.php',
success: function(resultarray) {
alert("success " + resultarray);
return levelarray;
},
error: function(xhr, status, error) {
//alert(xhr.responseText);
}
});
}
This alert("success " + resultarray); does return the array like it should.
But when i want to use it in my javascript it keeps saying it is undefined, or it does not say anything.
I tried it like this:
var test = getArray();
alert("result= "+ test);
So this Alert keeps returning me errors or empty values.
Does anyone know how i can do this?
Thank you in advance.
This is related to the asynchronous nature of javascript. Instead of using your function like
var test = getArray();
Try something along the lines of
function getArray(){
$.ajax({
url: 'Example.php',
success: function(resultarray) {
alert("success " + resultarray);
doSomethingWithMyTiles(resultarray);
},
error: function(xhr, status, error) {
//alert(xhr.responseText);
}
});
}
with
function doSomethingWithMyTiles(resultarray){
//do stuff
}
if you want to use the success result in another js function, put that function inside the success() of the ajax. ajax runs asynchronous, so it doesnt run in sequential order with other functions. just do something like:
$.ajax({
url: 'Example.php',
success: function(data) {
// myFunction(), do something here with data from ajax;
},
});

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

Returning value from javascript 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 created a javascript object and im trying to fetch som data from it.
Im using jquery ajax to fetch send some values and then returing them from a php script.
this works, but when i try to use an instanse of my javascript object to dispaly the value i get 'undefined'.
Object:
var getDBresults = (function () {
function getResult(url,TableName ,callback){
$.ajax({
url: url,
type: 'POST',
data: {
'table':TableName,
},
success: function(data){
callback(data);
},
error: function(event){
alert(event.error);
}
});
}
return {
getAllVideoes: function(){
getResult("getAllResults.php", "videoer", function(data){
console.log(data); //Works
return data;
});
},
}
})();
in my other script:
var obj = getDBresults;
var data = obj.getAllVideoes(); //this runs, and produce the log showed above
console.log(data) //results in undefined
console.log(obj.getAllVideoes()) //results in undefined
Maybe you can use callbacks it will solve your async problems: http://recurial.com/programming/understanding-callback-functions-in-javascript/

Load data asynchron in a JS 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 currently writing a JS class for my webshop application to access product information which is stored on the server. The information should be loaded asynchronously. For this I use dojo.xhrPost(). I want to rewrite a function for this class, called getProductName(productId:int):String which returns the product name for a given product id. The function uses intern dojo.xhrPost(). But whould should I return the loaded product name due to the fact that I have to pass new function to load and error in dojo.xhrPost()?
Usage of this function: Other JS functions call this to load the product name to update the cart webpage without reloading the whole page. The data returned is in JSON format due to the fact that some additional information is transferred for error handling (the client function has to know if any error occurred on server-side or not).
The code for the function getProductName(productId:int):
function getProductName(productId) {
dojo.xhrPost({
url: '/shop/dataProduct.php',
handleAs: 'json',
content: {productId:productId},
load: function(response, ioArgs) {
if (!response.error) {
// here I would like to return response.data to the caller of myObj.getProductName(productId)
} else {
// here I would like to return "error" to the caller of myObj.getProductName(productId)
}
return response;
},
error: function(response, ioArgs) {
// here I would like to return "error" to the caller of myObj.getProductName(productId)
return response;
}
});
}
The usage:
var productName = myObj.getProductName(5);
The problem with the following line of code is that it is assuming the the retrieval of the product name is synchronous. But you are making an ajax call to get the name and therefore the code is asynchronous.
var productName = myObj.getProductName(5);
You need to use dojo/Deferred to handle the asynchronous call.
function getProductName(productId) {
var d = new dojo.Deferred();
dojo.xhrPost({
url: '/shop/dataProduct.php',
handleAs: 'json',
content: {productId:productId},
load: function(response, ioArgs) {
if (!response.error) {
var productName = ???;
d.resolve(productName);
} else {
d.reject(response.error);
}
},
error: function(err) {
d.reject(err);
}
});
return d;
}
Usage:
getProductName(1).then(
function(productName) {
// do something with product name
}, function(error) {
// handle error
});
http://dojotoolkit.org/reference-guide/1.8/dojo/Deferred.html

Categories

Resources