How to Access Array response of AJAX - javascript

This is my AJAX call response which is in array format
[1,2,3,4,5,6]
success: function(outputfromserver) {
$.each(outputfromserver, function(index, el)
{
});
How can we access outputfromserver all values ??
Means outputfromserver Zeroth value is 1 , 2nd element is 2 , -----so on

It would help to know what your AJAX request looks like. I recommend using $.ajax() and specifying the dataType as JSON, or using $.getJSON().
Here is an example that demonstrates $.ajax() and shows you how to access the returned values in an array.
$.ajax({
url: 'test.json', // returns "[1,2,3,4,5,6]"
dataType: 'json', // jQuery will parse the response as JSON
success: function (outputfromserver) {
// outputfromserver is an array in this case
// just access it like one
alert(outputfromserver[0]); // alert the 0th value
// let's iterate through the returned values
// for loops are good for that, $.each() is fine too
// but unnecessary here
for (var i = 0; i < outputfromserver.length; i++) {
// outputfromserver[i] can be used to get each value
}
}
});
Now, if you insist on using $.each, the following will work for the success option.
success: function (outputfromserver) {
$.each(outputfromserver, function(index, el) {
// index is your 0-based array index
// el is your value
// for example
alert("element at " + index + ": " + el); // will alert each value
});
}
Feel free to ask any questions!

The array is a valid JSON string, you need to parse it using JSON parser.
success: function(outputfromserver) {
var data = JSON.parse(outputfromserver);
$.each(data, function(index, el) {
// Do your stuff
});
},
...

You can use JS objects like arrays
For example this way:
// Loop through all values in outputfromserver
for (var index in outputfromserver) {
// Show value in alert dialog:
alert( outputfromserver[index] );
}
This way you can get values at first dimension of array,
above for..loop will get values like this:
// Sample values in array, case: Indexed array
outputfromserver[0];
outputfromserver[1];
outputfromserver[2];
// So on until end of world... or end of array.. whichever comes first.
outputfromserver[...];
However, when implemented this way, by using for ( index in array ) we not only grab indexed 1,2,3,4,... keys but also values associated with named index:
// Sample values in array, case: accosiated/mixed array
outputfromserver["name"];
outputfromserver["phone"];
outputfromserver[37];
outputfromserver[37];
outputfromserver["myindex"];
// So on until end of world... or end of array.. whichever comes first.
outputfromserver[...];
In short, array can contain indexed values and/or name associated values, that does not matter, every value in array is still processed.
If you are using multidimensional stuff
then you can add nested for (...) loops or make recursive function to loop through all and every value.
Multidimensional will be something like this:
// Sample values in array, case: indexed multidimensional array
outputfromserver[0][0];
outputfromserver[0][1];
outputfromserver[1][0];
outputfromserver[1][...];
outputfromserver[...][...];
Update, JSON object:
If you server returns JSON encoded string you can convert it to javascript object this way:
try {
// Try to convert JSON string with jQuery:
serveroutputobject = $.parseJSON(outputfromserver);
} catch (e) {
// Conversion failed, result is not JSON encoded string
serveroutputobject = null;
}
// Check if object converted successfully:
if ( serveroutputobject !== null ) {
// Loop through all values in outputfromserver
for (var index in serveroutputobject) {
// Append value inside <div id="results">:
$('#results').append( serveroutputobject[index] + "<br/>" );
}
}
// In my own projects I also use this part if server can return normal text too:
// This way if server returned array we parse it and if server returns text we display it.
else {
$('#results').html( outputfromserver );
}
More information here

$.ajax({
type : "POST",
dataType: "json",
url : url,
data:dataString,
success: function(return_data,textStatus) {
temperature.innerText=return_data.temp;
// OR
**temperature.innerText=return_data['temp'];**
},
error: function(jqXHR, textStatus, errorThrown) {
alert("Error while accessing api [ "+url+"<br>"+textStatus+","+errorThrown+" ]"); return false;
}
});

Related

$.each function is not iterating

I am working with a relatively complex JSON structure and am unable to iterate through it via the $.each() function. I'm pretty sure it's something to do with the weird 2-dimensional array I am passing through in the value section of the normal array (hope that made sense). I am new to Ajax and JSON so just need some guidance on the best way to handle JSON when it is returned via an AJAX Call. Thanks!
$.ajax({
type: 'POST',
url: 'model.php',
data: formData,
dataType: 'json',
encode : true
}).done(function(data){
var i = 0;
for(var k in data){
window.alert(k);
} //this works
$.each(data, function(key, value){ //however this does not display anything
window.alert("should be outputted");
window.alert("key" + key + "value" + value[i]['email']);
i++;
});
});
JSON I am using:
{"bodge.com":[{"email":"mgbbuqc#bodge.com","orders":"2","value":"19.67"},{"email":"vswmdkqtb#bodge.com","orders":"5","value":"21.89"},{"email":"fwzqfjma#bodge.com","orders":"3","value":"13.71"},{"email":"rwsofs#bodge.com","orders":"7","value":"6.49"},{"email":"vfr#bodge.com","orders":"3","value":"24.36"},{"email":"wcs#bodge.com","orders":"3","value":"11.26"},{"email":"oqmsboag#bodge.com","orders":"3","value":"5.36"},{"email":"wdvm#bodge.com","orders":"6","value":"18.21"},{"email":"xubumenme#bodge.com","orders":"1","value":"10.24"},{"email":"pleqlwpha#bodge.com","orders":"2","value":"6.59"},{"email":"dqhdcnvw#bodge.com","orders":"10","value":"7.85"},{"email":"gyxymze#bodge.com","orders":"1","value":"15.51"},{"email":"otbbqcw#bodge.com","orders":"2","value":"7.92"},{"email":"afspqpq#bodge.com","orders":"3","value":"13.22"},{"email":"fwovyddw#bodge.com","orders":"4","value":"23.14"},{"email":"urczmgy#bodge.com","orders":"7","value":"15.17"},{"email":"hkgccna#bodge.com","orders":"4","value":"17.62"},{"email":"hlrnunyf#bodge.com","orders":"4","value":"22.03"},{"email":"gafoubu#bodge.com","orders":"10","value":"16.71"},{"email":"muwfjqs#bodge.com","orders":"4","value":"6.09"},{"email":"ddjeqvu#bodge.com","orders":"1","value":"23.88"},{"email":"jbq#bodge.com","orders":"8","value":"5.37"}],"bodge.com ":[{"email":"uytdlcgd#bodge.com ","orders":" 9 ","value":" 21.22"}]}
Your JSON has (at least) two levels:
an object with keys ("bodge.com", "bodge.com "), and
each key holds an array of objects
{
"bodge.com": [
{"email":"mgbbuqc#bodge.com","orders":"2","value":"19.67"},
{"email":"vswmdkqtb#bodge.com","orders":"5","value":"21.89"},
...
{"email":"ddjeqvu#bodge.com","orders":"1","value":"23.88"},
{"email":"jbq#bodge.com","orders":"8","value":"5.37"}
],
"bodge.com ": [
{"email":"uytdlcgd#bodge.com ","orders":" 9 ","value":" 21.22"}
]
}
In order to iterate through the structure, you will need at least two levels of iteration:
$.each(data, function(domain, objects) {
console.log(domain); // will output "bodge.com" or "bodge.com "
$.each(objects, function(index, x) {
console.log(x.email);
console.log(x.orders);
console.log(x.value);
console.log(index); // will output the 0-based position of x within the array
});
});
Note that you are using $.each for two different kinds of iteration: first over the keys and values of an object, then over the items in an array.
As an alternative, use Object.keys to get an array of an object's keys, and the forEach method:
Object.keys(data).forEach(function(domain) {
console.log(domain); // will output "bodge.com" or "bodge.com "
data[domain].forEach(function(x, index) {
console.log(x.email);
console.log(x.orders);
console.log(x.value);
console.log(index); // will output the 0-based position of x within the array
});
});
It looks like you should be bypassing data['bodge.com'] into the each function rather that simply data.
You could try this;
$.ajax({
type: 'POST',
url: 'model.php',
data: formData,
dataType: 'json',
encode : true
}).done(function(data){
var list = JSON.parse(data);
$.each(list, function(i){
alert(list[i].your_filed);
});
});

how to iterate each array element in response in $.ajax

First thing, the simple response which I get back from $.ajax is this:
http://pastebin.com/eEE72ySk
I am using this code:
$.ajax({
url: "/api/Flight/SearchFlight",
type: "Post",
data: $('form').serialize() + '&' + $.param({
'TokenId': $("#pageInitCounter").val()
}, true),
success: function(data) {
var result = JSON.parse(data);
$('#responsestatus').text(result.Response.ResponseStatus);
});
I was trying this code:
$.each(result.Response.Results[0][0].AirlineRemark, function (i, item) {
$("#divResult1").append('<p>' + item.AirlineRemark + '</p>');
});
When I use the above code, then error is:
Uncaught TypeError: Cannot use 'in' operator to search for '5' in IndiGo
When I tried this code without the forEach loop :
$("#divResult1").text(result.Response.Results[0][0].AirlineRemark);
I get no error but the output is only the first one. Indigo is showing however in response there are 20 arrays in Results. I have shown only two arrays in result in the link provided above.
Please someone tell me how to iterate each and every item in results array.
AirlineRemark is not an Array, so looping through that one is not possible. So loop through the array of arrays, and find the property within each loop
$.each(result.Response.Results[0], function (i, item) {
$("#divResult1").append('<p>' + item.AirlineRemark + '</p>');
});
You're trying to iterate a non-array there. If, result is based on your JSON that you provided. This is one way you can iterate it,
// Each items in result.Response.Results
$.each(result.Response.Results, function(i, items) {
// Get the AirlineRemark at the item at 0 index.
var airlineRemark = items[0].AirlineRemark;
// Append it to #divResult1
$("#divResult1").append('<p>' + airlineRemark + '</p>');
});
Beware that on sample above, items is an array. And it will only get the first item.
You can try this
$.each(result.Response.Results, function () {
$("#divResult1").append('<p>'+this[0].AirlineRemark+'</p>');
});

getJSON data add array item to variable

I am using this script to retrive JSON data from a file to my page.
$.getJSON('json/data.json', function(data) {
$('#getJSON-results').html(JSON.stringify(data));
});
<div id="getJSON-results"></div>
Right now it jsut displays all the data from JSON file as a string on the page.
How would I take the data from my JSON file and place each array into a variable? My data in the JSON file looks like this:
[{"target": "summarize(first, \"1d\", \"sum\")", "datapoints": [[38.393148148148143, 1423958400], [90.800555555555633, 1424044800], [159.06037037037032, 1424131200], [245.5933333333335, 1424217600], [126.94796296296299, 1424304000], [120.37111111111113, 1424390400], [103.04148148148151, 1424476800], [99.273796296296368, 1424563200], [89.38203703703708, 1424649600], [92.970462962963012, 1424736000], [105.62666666666664, 1424822400], [110.33962962962967, 1424908800], [118.54981481481482, 1424995200], [100.08018518518523, 1425081600], [92.52277777777779, 1425168000], [98.647619047618974, 1425254400], [94.585000000000008, 1425340800], [85.568796296296284, 1425427200], [157.82222222222222, 1425513600], [109.7596296296296, 1425600000], [112.53324074074077, 1425686400], [89.392592592592649, 1425772800], [97.253518518518518, 1425859200], [73.424629629629635, 1425945600], [92.377592592592578, 1426032000], [76.117870370370397, 1426118400], [77.83953703703699, 1426204800], [66.643518518518533, 1426291200], [63.748055555555531, 1426377600], [137.30018518518517, 1426464000], [53.480648148148134, 1426550400]]},
{"target": "summarize(second, \"1d\", \"sum\")", "datapoints": [[2.7291600529100535, 1423958400], [5.7797089947089892, 1424044800], [3.4261574074074059, 1424131200], [5.0516335978835958, 1424217600], [6.2272420634920582, 1424304000], [11.752605820105822, 1424390400], [7.8688624338624269, 1424476800], [5.7305555555555525, 1424563200], [5.2784391534391499, 1424649600], [6.4652380952380897, 1424736000], [4.7690277777777741, 1424822400], [4.1451587301587258, 1424908800], [8.4178902116402039, 1424995200], [4.7948611111111061, 1425081600], [4.8153835978835939, 1425168000], [5.3873148148148111, 1425254400], [7.2819378306878262, 1425340800], [5.2084391534391488, 1425427200], [8.098492063492051, 1425513600], [5.6563822751322697, 1425600000], [5.3091468253968195, 1425686400], [4.7850396825396793, 1425772800], [3.8716931216931179, 1425859200], [3.1934325396825369, 1425945600], [3.2083531746031722, 1426032000], [3.3434391534391512, 1426118400], [3.6162235449735438, 1426204800], [3.2094179894179891, 1426291200], [2.3699537037037026, 1426377600], [4.3973544973544945, 1426464000], [2.1901388888888893, 1426550400]]},
{"target": "summarize(third, \"1d\", \"sum\")", "datapoints": [[5.3710185185185182, 1423958400], [11.25367724867724, 1424044800], [8.2990079365079268, 1424131200], [8.710694444444437, 1424217600], [9.6381216931216898, 1424304000], [9.3845105820105807, 1424390400], [9.7305820105820047, 1424476800], [8.6268055555555474, 1424563200], [10.589166666666673, 1424649600], [10.235462962962957, 1424736000], [10.455892857142853, 1424822400], [14.282407407407405, 1424908800], [17.774404761904758, 1424995200], [18.154120370370364, 1425081600], [16.249543650793651, 1425168000], [15.29764550264551, 1425254400], [16.267671957671972, 1425340800], [20.121488095238096, 1425427200], [27.007685185185196, 1425513600], [17.577962962962971, 1425600000], [17.020873015873018, 1425686400], [14.627685185185191, 1425772800], [15.824821428571433, 1425859200], [11.837579365079364, 1425945600], [13.292539682539683, 1426032000], [12.064074074074073, 1426118400], [12.279457671957676, 1426204800], [9.3799074074073978, 1426291200], [7.8777314814814732, 1426377600], [13.161825396825407, 1426464000], [7.2587499999999956, 1426550400]]}]
I am new to using JSON and would also appreciate any advice on the approach I'm taking.
How can I now make this data accsessable outside the getJSON?
$.getJSON('json/data.json', function(data) {
yourData = data;
makeMeGlobal = yourData[0];
});
console.log(makeMeGlobal.datapoints);
Changing your function to the following will result in an object you can then reference normally:
$.getJSON('json/data.json', function(data) {
yourData = data;
});
You could then get the first set of datapoints like this:
yourData.datapoints[0]
Should be:
data.forEach(function (obj) {
// obj now has each JSON object in this array
var test = obj.target;
}
When you get a JSON from AJAX, it's already ready for use in the browser. This is one of the nice perks of using JSON over XML.
It's already an array, because the original JSON string was parsed by jQuery. If you use stringify, you will get a string which contains the JSON representing the array (not useful for your purposes, as it's the same string returned by the server).
For example:
$.getJSON('json/data.json', function(data) {
// Here, data is already an array.
var data_length = data.length;
for (var i = 0; i < data_length; i++) {
var obj = data[i]; // Here we have an object from the array
alert("I have an object which target is " + obj.target);
}
});
You need to iterate through json to retrieve the value you need and append the html.More infor # https://stackoverflow.com/a/18238241/909535 Something like this
`$.getJSON('json/data.json', function(data){
data.forEach(
function(val, index, array) {
//val.target will have target attribute's value
//val.datapoints is a array which you can iterate
}
);
}
);`

display specific object values in an array instead of individually?

I have used an ajax call to retrieve data from Googles places api and I have used a for/in loop to begin to pull the information. the information that I am looking for logs to the console, but I cannot get it to display in an array how I would like it to.
Right now I am getting a list of names when I request names which is a parameter in the JSON object. Is there a way to get it into an array so the I can randomly select one of the values from the array?
at this point the way it is returning my data, when I run a script to pull a random string, it pulls a random letter out of the last value to be found when searching through my JSON object.
Here is my code. Not sure if I explained myself clearly but it's the best that I could word what I am looking to do. Thanks.
// **GLOBAL VARIABLES** //
// Chosen Restaurant display area
var display = document.getElementById('chosenVenue');
// Grab button
var button = document.getElementById('selectVenue');
// Sample Array that gets queried
var venueData = ["McDonalds", "Burger King", "Wendys"];
// Grab JSON data from Google
$(document).ready(function(){
$.ajax({
url: 'hungr.php', // Send query through proxy (JSONP is disabled for Google maps)
data: { requrl: "https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=40.7484,-73.9857&radius=800&sensor=false&keyword=restaurants,food&key=AIzaSyBkCkXIHFjvqcqrRytSqD7T_RyFMNkR6bA&callback=?"}, // URL to query WITH parameters
dataType: "json",
type: "GET", // or POST if you want => update php in that case
success: function (data) {
// Traverse the array using for/in loop using i as var
for (var i in data.results) {
var results = data.results[i];
var nameResults = results.name;
console.log(nameResults);
var typesResults = results.types;
console.log(typesResults);
var vicinityResults = results.vicinity;
console.log(vicinityResults);
};
// On button click, randomly display item from selected array
button.addEventListener('click', function () {
console.log('clicked');
display.style.display = 'block';
//display.innerHTML = nameResults[Math.floor(Math.random() * nameResults.length)];
display.innerHTML = nameResults.toString() + "<br />" + vicinityResults.toString();
});
console.log('It is working');
},
error: function (request, status, error) {
console.log('It is not working');
}
});
});
Right now I am getting a list of names when I request names which is a parameter in the JSON object. Is there a way to get it into an array so the I can randomly select one of the values from the array?
Use the push method and a non-local variable:
this.nameResults = this.nameResults ? this.nameResults.push(results.name) : [];
then reference that with the Math.random method:
this.randName = function(){ return this.nameResults[Math.random() * this.nameResults.length | 0] };
References
Using Math.random flexibly
JavaScript: fast floor of numeric values using the tilde operator

how to browse a javascript object

I'm new to jQuery. Following is the data variable that contains a json dictionary.
{
"user":null,
"currency":"EUR",
"balance":0,
"translist": [
{ "trans1":"something","trans2":"something2" }
]
}
and my jQuery method receives a json/Javascript object from the Rest GET call
success: function (data){
for(x in data) {
console.log(x + ': ' + data[x]);
}
});
Is there any library that can help to parse/walk through this json object and get to some kind of objects list? I want to check some of the keys and their respective values. Problem is I don't need all the keys and values from the list and also some of the values can be null, which prevented me to apply some solutions I found using SO.
Or usually is it more common to directly start printing the HTML inside the success function?
EDIT:If it was java for example it would be a Map and I would use an iterator to walk through and see/analyse the map values, and create some array list with the values I want from it. What's equivalent of that in jQuery?
If it was java for example it would be a Map and I would use an
iterator to walk through and see/analyse the map values, and create
some arraylist with the values I want in it. What is the equivalent of that
in jQuery?
Any javascript object can be seen as an associative map.
You can for example directly access the currency as data['currency'].
You can also build an array :
var a = [];
for (var key in data) {
a.push({key:key, value:data[key]});
}
You could also build some HTML and apply functions to the data :
$(document.body).append($(
'<table>' + a.map(function(v){
return '<tr><td>'+v.key+'</td><td>'+v.value+'</td></tr>'
}).join('')+'</table>'
));
Demonstration
Using jQuery can make the same iteration simpler (working directly from data) :
$(document.body).append($(
'<table>' + $.map(data, function(value,key){
return '<tr><td>'+key+'</td><td>'+value+'</td></tr>'
}).join('')+'</table>'
));
Demonstration
Try using each
success: function (data){
$.each( data, function( key, value ) {
if(key === "currency")
alert( key + ": " + value );
});
});

Categories

Resources