loop for fetching json data in html [duplicate] - javascript

On the jQuery AJAX success callback I want to loop over the results of the object. This is an example of how the response looks in Firebug.
[
{"TEST1":45,"TEST2":23,"TEST3":"DATA1"},
{"TEST1":46,"TEST2":24,"TEST3":"DATA2"},
{"TEST1":47,"TEST2":25,"TEST3":"DATA3"}
]
How can I loop over the results so that I would have access to each of the elements?
I have tried something like below but this does not seem to be working.
jQuery.each(data, function(index, itemData) {
// itemData.TEST1
// itemData.TEST2
// itemData.TEST3
});

you can remove the outer loop and replace this with data.data:
$.each(data.data, function(k, v) {
/// do stuff
});
You were close:
$.each(data, function() {
$.each(this, function(k, v) {
/// do stuff
});
});
You have an array of objects/maps so the outer loop iterates over those. The inner loop iterates over the properties on each object element.

You can also use the getJSON function:
$.getJSON('/your/script.php', function(data) {
$.each(data, function(index) {
alert(data[index].TEST1);
alert(data[index].TEST2);
});
});
This is really just a rewording of ifesdjeen's answer, but I thought it might be helpful to people.

If you use Fire Fox, just open up a console (use F12 key) and try out this:
var a = [
{"TEST1":45,"TEST2":23,"TEST3":"DATA1"},
{"TEST1":46,"TEST2":24,"TEST3":"DATA2"},
{"TEST1":47,"TEST2":25,"TEST3":"DATA3"}
];
$.each (a, function (bb) {
console.log (bb);
console.log (a[bb]);
console.log (a[bb].TEST1);
});
hope it helps

For anyone else stuck with this, it's probably not working because the ajax call is interpreting your returned data as text - i.e. it's not yet a JSON object.
You can convert it to a JSON object by manually using the parseJSON command or simply adding the dataType: 'json' property to your ajax call. e.g.
jQuery.ajax({
type: 'POST',
url: '<?php echo admin_url('admin-ajax.php'); ?>',
data: data,
dataType: 'json', // ** ensure you add this line **
success: function(data) {
jQuery.each(data, function(index, item) {
//now you can access properties using dot notation
});
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert("some error");
}
});

Access the json array like you would any other array.
for(var i =0;i < itemData.length-1;i++)
{
var item = itemData[i];
alert(item.Test1 + item.Test2 + item.Test3);
}

This is what I came up with to easily view all data values:
var dataItems = "";
$.each(data, function (index, itemData) {
dataItems += index + ": " + itemData + "\n";
});
console.log(dataItems);

Try jQuery.map function, works pretty well with maps.
var mapArray = {
"lastName": "Last Name cannot be null!",
"email": "Email cannot be null!",
"firstName": "First Name cannot be null!"
};
$.map(mapArray, function(val, key) {
alert("Value is :" + val);
alert("key is :" + key);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

if you don't want alert, that is u want html, then do this
...
$.each(data, function(index) {
$("#pr_result").append(data[index].dbcolumn);
});
...
NOTE: use "append" not "html" else the last result is what you will be seeing on your html view
then your html code should look like this
...
<div id="pr_result"></div>
...
You can also style (add class) the div in the jquery before it renders as html

I use .map for foreach. For example
success: function(data) {
let dataItems = JSON.parse(data)
dataItems = dataItems.map((item) => {
return $(`<article>
<h2>${item.post_title}</h2>
<p>${item.post_excerpt}</p>
</article>`)
})
},

If you are using the short method of JQuery ajax call function as shown below, the returned data needs to be interpreted as a json object for you to be able to loop through.
$.get('url', function(data, statusText, xheader){
// your code within the success callback
var data = $.parseJSON(data);
$.each(data, function(i){
console.log(data[i]);
})
})

I am partial to ES2015 arrow function for finding values in an array
const result = data.find(x=> x.TEST1 === '46');
Checkout Array.prototype.find() HERE

$each will work.. Another option is jQuery Ajax Callback for array result
function displayResultForLog(result) {
if (result.hasOwnProperty("d")) {
result = result.d
}
if (result !== undefined && result != null) {
if (result.hasOwnProperty('length')) {
if (result.length >= 1) {
for (i = 0; i < result.length; i++) {
var sentDate = result[i];
}
} else {
$(requiredTable).append('Length is 0');
}
} else {
$(requiredTable).append('Length is not available.');
}
} else {
$(requiredTable).append('Result is null.');
}
}

Related

JSON values are showing NaN

While retrieving JSON array data using $.each method, I am able to get the array values, but apart from that it's showing 'NaN' values and showing the below error.
"Uncaught TypeError: Cannot use 'in' operator to search for '5' in Hello!"
Seems it's looping through all the objects not only array, if this is the case how can I get only array values and how can I get all the values(including and excluding array values).
one more query does this rawgit works for only method 'GET', because while using method 'POST' throwing error(403 (Forbidden)).
$.ajax({
method: 'GET',
url: 'https://rawgit.com/rajeshdesigner/testgit/master/colorsdata.json',
dataType: 'json',
success: function (data) {
$.each(data, function(index, obj){
$.each(obj, function(index, element) {
$('#show-data').append(element.key + element.value + '<br/>');
});
});
}
});
JSON:
{
"items": [
{
"key": "First",
"value": 100
},{
"key": "Second",
"value": 200
},{
"key": "Last",
"value": "Mixed"
}
],
"obj": {
"number": 1.2345e-6,
"enabled": true
},
"message": "Hello!"
}
It sounds like you only want to iterate data.items but you're iterating over everything. Try this:
$.each(data.items, function(index, obj) {
$('#show-data').append(obj.key + obj.value + '<br/>');
});
https://jsfiddle.net/rrsku4Lq/
The problem is when the second loop reaches "message": "Hello!", that is not a object to be looped again, so for that element only the first loop is needed.
To correct, just make an if statement to enter the second loop only in case obj is an Object.
I also changed the nested loop index name to index2.
$.each(data, function(index, obj){
// Only do nested loop if obj is Object
if (obj instanceof Object) {
$.each(obj, function(index2, element) {
$('#show-data').append(element.key + element.value + '<br/>');
});
}
});
If you're only interested in data.items, than you can use
$.each(data.items, function(index2, element) {
$('#show-data').append(element.key + element.value + '<br/>');
});
You have an unnecessary for loop. The response is one JSON object in your case. You simply need to iterate the data items. UPDATE: How you handle a response depends on what you want to accomplish. In practice, you'll generally know how to access the data you need from the response, but as others have suggested, you can iterate through the keys in the response object and check for types
var object = {
arr : [1,2,3],
nestedObject : { }
};
for (var key in object) {
console.log(key);
console.log('Is array? ' + Array.isArray(object[key]));
// Now you can handle the data based on it's type...
}
In this case, you could choose to expect the response to include a items key and iterate over that. (It's also good practice to validate that you can process the response)
$.ajax({
method: 'GET',
url: 'https://rawgit.com/rajeshdesigner/testgit/master/colorsdata.json',
dataType: 'json',
success: function(data) {
// data is your JSON object.
data.items.forEach(function(item) {
$('#show-data').append(item.key + item.value + '<br/>');
});
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="show-data"></div>
Also, 403 indicates that the resource is blocked for the current user. Verify that your POST method is publicly accessible and that you are authorized to make the request.
You should parse the json first. And as #Jason P said, iterate data.items
$.ajax({
method: 'GET',
url: 'https://rawgit.com/rajeshdesigner/testgit/master/colorsdata.json',
dataType: 'json',
success: function (data) {
var parsedData = $.parseJSON(data);
$.each(parsedData.items, function(index, obj){
$.each(obj, function(index, element) {
$('#show-data').append(element.key + element.value + '<br/>');
});
});
}
});
You are looping through all the elements in the array. I think you need to loop through only 'items' element as only that element contains the 'key' and 'value' elements.
Even though you are doing that, you can check if the key and value element exists, and if it does, do whatever your code wants.
$.ajax({
method: 'GET',
url: 'https://rawgit.com/rajeshdesigner/testgit/master/colorsdata.json',
dataType: 'json',
success: function (data)
{
$.each(data, function(index, obj)
{
$.each(obj, function(index, element)
{
if(element.hasProperty('key') && element.hasProperty('value'))
$('#show-data').append(element.key + element.value + '<br/>');
});
});
}
});
$.ajax({
method: 'GET',
url: 'https://rawgit.com/rajeshdesigner/testgit/master/colorsdata.json',
dataType: 'json',
success: function (data) {
console.log(data.items);
$.each(data.items, function(index, element) {
$('#show-data').append(element.key + element.value + '<br/>');
});
}
});

$.getJSON() to $.ajax()

I would like to ask how could I convert the following $.getJSON() to $.ajax() please.
I have a set of arrays from var googleApi like this:
Array [Object, Object, Object, Object, Object]
// if stringified
[{"id":"0","name":"user1","type":"mf","message":"bonjour user1"},
{"id":"1","name":"user2","type":"ff","message":"hello user2"},
{"id":"2","name":"user3","type":"mm","message":"konnichiwa user3"},
{"id":"3","name":"user4","type":"mf","message":"ni hao user4"},
{"id":"4","name":"user5","type":"ff","message":"high 5! user5"}]}
I would like to ask how could I identify if the value of a declared variable (eg. content with the value of user1) is the same as a value within the list of name keys in the array?
Below is my attempt and you might find my full code in $.getJSON() here:
$.getJSON():
var googleApi = 'https://api.com/url_here';
$.getJSON(googleApi, function(json){
console.log(JSON.stringify(json));
var item = json.result.find(function(e){
return e.name == content;
}) || json.result[0];
console.log("PRINT ID: " + item.id);
var name = item.name || content;
$('#nameText').text(name);
console.log("Name: " + name);
});
Below is my attempt on $.ajax() but I got an error of "TypeError: data.result is undefined";I have also tried using $(this) to replace data.result but without luck... it would be very nice if someone could identify what have I done wrong please:
var googleApi = "https://sheetsu.com/apis/v1.0/f924526c";
var googleKey = "0123456789";
var googleSecret = "987654321";
var data = [];
$.ajax({
url: googleApi,
headers: {
"Authorization": "Basic " + btoa(googleKey + ":" + googleSecret)
},
data: JSON.stringify(data),
dataType: 'json',
type: 'GET',
success: function(data) {
console.log(data);
var item = data.result.find(function(e){
return e.name == content;
}) || data.result[0];
console.log("PRINT ID: " + item.id);
var name = item.name || content;
$('#nameText').text(name);
console.log("Name: " + name);
});
Merci beaucoup :))) x
...how could I identify if the value of a declared
variable ... is the same as a value
within the list of name keys in the array?
As per your provided response object you could iterate through it and check the values against your variable content:
var content = "user1";
$.each(response, function(i, v) {
if (v.name == content) {
console.log(v.name);
}
});
Example Fiddle
As for the second part of your question:
but I got an error of "TypeError: data.result is undefined";
The reason you may be getting your error is because find is expecting a jQuery object, you have received a JSON object back from your endpoint, so using dot notation as above will should work as well:
success: function(data) {
$.each(data, function(i, v) {
if (v.name == content) {
console.log(v.name);
}
});
}
You can see the answer to this question for a bunch of awesome information on how to access / proccess objects.
Also note your success callback in your code above is not closed, which will create errors.
function getID(name){
$.each(data,function(key,value){ //value = object.value (name)
$.each(value,function(key1,value1){ //value1 = user name (actual names in array)
if(value1 == content){
console.log(value.id);
var name = value.name;
$('#nameText').text(name);
console.log("Name: " + name);
return;
}
});
});
}
getID(data);
return false;

Javascript global variables only accessible after application runs

I have a series of nested Ajax requests to external APIs, which is very ugly but it was the only way I could figure out how to make calls in a specified order with each call utilizing some values brought back from the previous call. (I attempted this but couldn't get it to work, so I reverted to the advice here.)
Anyway, this works well to a point. All my calls work in succession, and I end up with an array called people, which is just a list of names: ["name1","name2","name3"].
My problem is that I don't seem to be able to do anything with this array from my javascript code. I can't append them to a div, nor can I alert them, or even console.log them during code execution. However, once my code completes, I can type people into the browser console and there they all are, as expected.
I am guessing this has something to do with the scope of the variable - I have tried making it global and moving the placement of its declaration, but the only way I can access people from the runnable code is from within the final AJAX loop, and then I get lots of repeating values because it's looping and adding to the array incrementally.
The goal here is to get people from that final API call and list them in HTML.
Here's my code. Any suggestions greatly appreciated.
HTML to trigger event:
<input type='file' accept='image/*' onchange='openFile(event)'>
<!--process is triggered by file upload-->
javascript:
var openFile = function(event) {
//... Some UI stuff happens here.
//... When finished, just call getGraph(); below
performances = new Array(); // global scope
people = new Array(); // global scope
getGraph(); // call function below
console.log(people); // retrieve array; doesn't work
};
function getGraph(){
$.ajax({
url:'http://...' + document.getElementById('prDate').value,
dataType:'json',
success: function(response){
$.each(response, function(i, item) {
var programID = item.id;
$.ajax({
url:'http://...'+ programID',
dataType:'json',
success: function(response){
$.each(response, function(i, item) {
performances.push( item.id );
});
$.each(performances, function(index, value){
$.ajax({
url:'http://...' + this.valueOf() +'/persons/',
dataType:'json',
success: function(response){
$.each(response, function(i, item) {
people.push( item.firstname + ' ' + item.lastname ); // the magic moment
});
}
});
});
}
});
});
}
});
}
From your code it is visible that people variable will be create only once you call openfile function. If you want it be created even when the openfile method is not called then declare it outside of all the functions and then it will be accessible or else declare it in the place where you intend to use it like above the ajax call, then use it.
Have you tried putting it inside a IIFE closure ?
(function(){
var OpenFile = function() {
if ( !(this instanceof OpenFile) ) {
return new OpenFile();
}
var performances = new Array(); // closure Scope
var people = new Array(); // closure Scope
function getGraph(){
$.ajax({
url:'http://...' + document.getElementById('prDate').value,
dataType:'json',
success: function(response){
$.each(response, function(i, item) {
var programID = item.id;
$.ajax({
url:'http://...'+ programID',
dataType:'json',
success: function(response){
$.each(response, function(i, item) {
performances.push( item.id );
});
$.each(performances, function(index, value){
$.ajax({
url:'http://...' + this.valueOf() +'/persons/',
dataType:'json',
success: function(response){
$.each(response, function(i, item) {
people.push( item.firstname + ' ' + item.lastname ); // the magic moment
});
}
});
});
}
});
});
}
});
}
return {
get performances() : { return performances;},
get people() : { return people; },
getGraph : getGraph
};
};
window.OpenFile = OpenFile;
})();
which you can then call by doing something like
var myOpenFile = new OpenFile();
var people = myOpenFile.people;
myOpenFile.getGraph();
console.log(people);
with the added benefit that the OpenFile object is immediately available after the code loads. All the variables inside the code are only scoped to the object OpenFile and don't pollute the global namespace and you can choose what you wish to expose to others by putting them in the return statement at the end.

Return Only Specific Values From Ajax JSON call

I'm having trouble with filtering the returned data from an Ajax JSON call. Right now, it returns:
{"results":[{"text":"RoboChat: What is it like to feel?","username":"RoboChat","createdAt":"2014-06-04T20:01:15.268Z","updatedAt":"2014-06-04T20:01:15.268Z","objectId":"wG2cs1OnVY"},
I'm trying to get it to return only the "text" object, like this:
"RoboChat:What is it like to feel?"
Here is my code:
function fetch () {
$.ajax({
url:"https://api.parse.com/1/classes/chats",
type : 'GET',
dataType : 'JSON',
data : JSON.stringify({
}),
success:function(data) {
$('.messages').append("<li>" + (JSON.stringify(data)) + "</li>")
}
});
};
I've tried passing a filter to JSON.stringify, but with no success, I'm not even sure if that's the way to approach filtering the data. Any help would be much appreciated.Thanks!
You can't really change what a request returns, but you can of course use the resulting value in any way you want. Since the response contains multiple objects with text properties, you have to iterate them and extract the text:
success: function(data) {
var results = data.results;
results.forEach(function (result) {
$('.messages').append("<li>" + result.text + "</li>");
});
}
The returned JSON has a results property which is an array, you can iterate through the array and read the text property of each element:
$.each(data.results, function(index, element) {
console.log(element.text);
});
For creating a li element for each array's element, you can use the $.map utility function:
var li = $.map(data.results, function(element) {
return '<li>' + element.text + '</li>';
});
$('.messages').append(li);
try for, the data has an array named results, from wich you have to select the first like following:
success: function(data) {
var results = JSON.parse(data).results;
results.forEach(function (result) {
$('.messages').append("<li>" + data.results[0].text + "</li>");
});
}

Parse json object of multidimensional array

{
"prev": [
"demo/medium/Web081112_P002_medium.jpg",
"demo/medium/Web081112_P003_medium.jpg"
],
"curr": [
"demo/medium/Web081112_P004_medium.jpg",
"demo/medium/Web081112_P005_medium.jpg"
],
"next": [
"demo/medium/Web081112_P006_medium.jpg",
"demo/medium/Web081112_P007_medium.jpg"
]
}
This is the json I got :
<script>
$(document).ready(function(){
$.ajax({
type: "GET",
url: "scandir.php",
data: "page=5",
dataType: 'json',
success: function (data) {
$.each(data, function(i, data){
$('#img'+i).attr('src',data[1]);
});
}
});
});
</script>
I would like to do this: Assign <img id = "img1" src="demo/medium/Web081112_P002_medium.jpg"> and so on....
The collected data [1] only capture the values in column (3,5,7) . How to implement this? Thanks
since your are just setting the src attribute of the second data object here...
$('#img'+i).attr('src',data[1]);
you are getting the (3,7,5) only...
you have to use two $.each loops to get all the src..
try this
var k=1;
$.each(data, function(i, data1){
$.each(data1, function(j, data2){
$('#img' + k).attr('src', data2);
k++;
});
});
Try this if your array always has two elements:
$.each(data, function(i, data){
$('#img'+(2*i)).attr('src',data[0]);
$('#img'+(2*i + 1)).attr('src',data[1]);
});
If you have more than two, then you'll need an inner loop:
var idx = 0;
$.each(data, function(i, data) {
$.each(data[i], function(j, dataj) {
$('#img'+(idx)).attr('src',dataj[j]);
++idx;
});
});
That's not a multidimensional array, that is an object that has arrays as properties.
To loop through the arrays, you need another loop inside the loop. Use a separate counter to keep track of the image numbering.
var count = 1;
$.each(data, function(i, row){
$.each(row, function(j, item){
$('#img' + count).attr('src', item);
count++;
});
});
Note: There is no specific order to the properties in an object, so they may end up in different order depending on which browser the visitor is using.

Categories

Resources