From Json Get vlaue of key Javascript - javascript

I am trying to do an api call to get a list of subcategories.
my json looks like this
{
"description": "Flower",
"name": "Flower",
"parent_id": "1"
},
{
"description": "Moon",
"name": "Moon",
"parent_id": "1"
}
]
This is what i have attepted so far.
<script type="text/javascript">
$('button').click(function() {
$.ajax({
url: "/api/subcategories?sstr=ball",
dataType: 'json',
type: "GET"
})
.done(function(data) {
$('.results').append('<ul class="list"></ul>');
$.each(data, function(key, value) {
console.log(data)
$('.list').append('<li>' + key + ': ' + value + '</li>');
});
})
.fail(function(event) {
alert(event.status);
});
});
</script>
The result i get is
0: [object Object]
1: [object Object]
2: [object Object]
what i would like is the list of names.

Where value is the array element which is an object instead get its name property.
$('.list').append('<li>' + key + ': ' + value.name + '</li>');
Since it's an array you can use JavaScript Array#forEach method also.
data.forEach(function(value, key) {
$('.list').append('<li>' + key + ': ' + value.name + '</li>');
});
Or you can reduce it to a single append statement by generating the HTML string using Array#map and Array#join methods.
$('.results').append(
'<ul class="list">' +
data.map(function(value, key) {
return '<li>' + key + ': ' + value.name + '</li>');
}).join('') +
'</ul>'
);

First you need to parse your json string to convert it in a javascript array.
So do this -> var json_data = jQuery.parseJSON(data);
Now,
var html = "";
html += '<ul>';
$.each( json_data, function( key, value ) {
html += '<li>'+key+':'+value['name']+'</li>';
});
html += '</ul>';
$('.list').html(html);
I think that will do the trick.

Related

Adding django view result from ajax as table in template

I have a django model and I view i am aggregating few columns and filtering result and returning as below
def show_grid_summery(request):
id = request.GET.get('id', None)
context = {
"summery": [],
}
result = Records.objects.filter(grid_id_id = id).aggregate(Sum('house_count'), Sum('point_count'))
if len(result) != 0:
context["summery"].append([result['house_count__sum'], result['point_count__sum']])
return JsonResponse(context)
And on the template i am getting results using ajax
$.ajax({
url: 'ajax/summery/',
data: {
'id': ID
},
dataType: 'json',
success: function (data) {
alert(data);
var trHTML = '';
document.getElementById('summaryLabel').innerHTML = '';
$.each(data.summery , function (item) {
trHTML += '<tr><td>' + item[0] + '</td><td>' + item[1] + '</td></tr>';
});
$('#summaryLabel').append(trHTML);
}
Now I want to fill the results record (2 columns) as a table inside the #summaryLabel tag. (preferably with headers as well). But I am unable to sort it out after many different attempts.
html part is
<table id="summaryLabel">
<p>information.</p>
</table>
The jQuery $.each() function passes two parameters, the first is the array index, the second is the object. So it would seem that in your code, your item variable would contain the index, which is not what you want.
Try:
$.each(data['summery'] , function (i, item) {
trHTML += '<tr><td>' + item[0] + '</td><td>' + item[1] + '</td></tr>';
});
or just
$.each(data['summery'] , function () {
trHTML += '<tr><td>' + this[0] + '</td><td>' + this[1] + '</td></tr>';
});
jQuery $.each() is documented here: http://api.jquery.com/jquery.each/

ordered list; working with javascript and json

I'm a junior web developer and I want to understand what json file does, as I have no idea. So I am following a tutorial from lynda.com
It seems very simple, I want to display the array elements within the variable info, but for some reason, it's adding another count after each item of the array!!! I have checked and compared the code with the tutorial, and it's still appearing wrong.
I have added the code on JSFiddle:
https://jsfiddle.net/meyvz462/
Those are my loops:
for (var i = 0; i <= info.links.length; i++) {
for (key in info.links[i]) {
if (info.links[i].hasOwnProperty(key)) {
output += '<li>' +
'<a href = "' + info.links[i][key] +
'">' + key + '</a>' +
'<li>';
} // hasOwnProperty ckeck
} //for each object
} //for each array element
I guess it is what it must be wrong....
Thank you!!!!
The closing tag is wrong.
output += '<li>' +
'<a href = "' + info.links[i][key] +
'">' + key + '</a>' +
'<li>';
has to be
output += '<li>' +
'<a href = "' + info.links[i][key] +
'">' + key + '</a>' +
'</li>';
You have missed a closing </li> at the end (https://jsbin.com/yasenivege/1/edit?js,console,output):
var info = {
"full_name" : "Someone Else",
"title" : "Web Developer",
"links" : [
{ "blog" : "http://iviewsource.com" },
{ "facebook" : "http://facebook.com/iviewsource" },
{ "podcast" : "http://feeds.feedburner.com/authoredcontent" },
{ "twitter" : "http://twitter.com/planetoftheweb" },
{ "youtube" : "http://www.youtube.com/planetoftheweb" }
]
};
var output = '';
for (var i = 0; i <= info.links.length; i++) {
var element = info.links[i];
for (var key in element) {
console.log(element[key]);
if (element.hasOwnProperty(key)) {
output += '<li>' +
'<a href = "' +element[key] +
'">' + key +'</a>'+
'</li>';
}// hasOwnProperty ckeck
} //for each object
} //for each array element
var update = document.getElementById('linksGroup');
console.log(output)
update.innerHTML = output;

Hyperlinking URL value in JSON file

How can I set the URL value in my JSON file to a hyperlink when displayed in the table?
JSON
{
"one": "http://urltovideo.mp4",
"two": "The second list item",
"three": "The third list item"
}
jQuery
$.getJSON( "test.json", function( data ) {
var items = [];
$.each( data, function( key, val ) {
items.push( "<div class='panel panel-default'><div class='panel-heading'>" + key + "</div><div
class='panel-body'><a href=''>" + val + "</a></li></div></div>" );
});
$( "<ol/>", {
"class": "my-new-list",
html: items.join( "" )
}).fadeIn(900).appendTo( "body" );
});
You need to check if val is containing a link:
$.each( data, function( key, val ) {
var link = (val.indexOf('http') > -1) ? '' + val + '' : val;
items.push( '<div class="panel panel-default"><div class="panel-heading">' + key + '</div><div
class="panel-body">' + link + '</li></div></div>');
});
Also, for cleaner code, you should use " for HTML attributes like class="..." and ' for Javascript strings, like: '<a href="' + val + '">'
See jsFiddle

how to display json content in li format in phonegap

i can get the json in the following format
[{"data":{"id":"1","user_name":"StudentA","book":"123","role":"Student"}},
{"data":{"id":"3","user_name":"StudentB","book":"456","role":"Student"}}]
how can i use the data to present like the image below, where the first line is username and second line is book
<button type="button" id="test">Test 123</button>
<ul id="studentList" data-role="listview" data-filter="true"></ul>
var serviceURL = "http://mydomain.com/";
var students;
$("#test").click(function()
{
getStudentList();
});
function getStudentList() {
$.getJSON(serviceURL + 'getStudents.php', function(data) {
$('#studentList li').remove();
students = data.user_name;
$.each(students, function(index, student) {
$('#studentList').append('<li>' +
'<h4>' + student.user_name + ' ' + student.password + '</h4>' +
'<p>' + student.user_name + '</p>' +
'</li>');
});
$('#studentList').listview('refresh');
});
}
may i ask if the codes above correct?
you are naming response as data..since you response is in array [] you have to loop data first.. get its object which is data again ..
[{"data":{"id":"1","user_name":"StudentA","book":"123","role":"Student"}},
//-^^^^---here
and get the correponding name and password object in the loop...you can get that by . operator.. so inside loop, student.data.user_name gives you username , student.data.book gives you book and similar for others...
try this...
$.getJSON(serviceURL + 'getStudents.php', function(data) {
$('#studentList li').remove();
//students = data.user_name;
$.each(data, function(index, student) {
$('#studentList').append('<li>' +
'<h4>' + student.data.user_name +'</h4>' + //here get username
'<p>' + student.data.book + '</p>' + //here get book
'</li>');
});
$('#studentList').listview('refresh');
});
I have done it like that based on your input, you just need to include it into your code. I don't know what you mean by 'second line is book' since there is no book included in your json input + you are trying to access 'student.data.password' which is also not present in input.
Simple version of jsFiddle http://jsfiddle.net/2KMd9/
var json =[{"data":{"id":"1","user_name":"StudentA","book":"123","role":"Student"}},
{"data":{"id":"3","user_name":"StudentB","book":"456","role":"Student"}}];
var students = json;
$.each(students, function(index, student) {
$('#studentList').append('<li>' +
'<h4>' + student.data.user_name + '</h4>' +
'<p>' + student.data.role + '</p>' +
'</li>');
});
So for your needs:
function getStudentList() {
$.getJSON(serviceURL + 'getStudents.php', function(data) {
$('#studentList li').remove();
$.each(data, function(index, student) {
$('#studentList').append('<li>' +
'<h4>' + student.data.user_name + '</h4>' +
'<p>' + student.data.role + '</p>' +
'</li>');
});
$('#studentList').listview('refresh');
});
}

Target Specific Javascript Object Literal fields and array with jquery

I cant seem to get this to work. Im trying to do two things
A). Get the following code to show up correctly. The first element is show 'undefined
<ul>
<li>Button
<ul>
<li>x:1</li>
<li>y:2</li>
<li>width:3</li>
<li>height:4</li>
</ul>
</ul>
Here is my code:
$(document).ready(function() {
var data = {
"Controls": [{
"Button":[{ "x": "1","y": "2","width": "3","height": "4" }],
"Image":[{"x": "5","y": "6","width": "7","height": "8"}],
"TextField":[{"x": "9","y": "10","width": "11","height": "12"}]
}]
}
var str = '<ul>';
$.each(data.Controls, function(k, v) {
str += '<li>' + k[0] + '</li><ul>';
for(var kk in v.Button[0]){
str += '<li>' + kk + ':' + v.Button[0][kk] + '</li>';
}
str += '</ul>';
});
str += '</ul>';
$('div').append(str);
})
And
B). trying to display a list(separate list from above) of just the fields. like this:
<li>Button</li>
<li>Image</li>
<li>TextField</li>
I think that the answer to the second lies in the first, but I cannot seem to get the targeting right.
Any help is appreciated
Demo
To get the first list:
var str = '<ul>';
var target = "Button";
str += '<li>' + target + '<ul>';
$.each(data.Controls[0][target][0], function(kk, vv){
str += '<li>' + kk + ':' + vv + '</li>';
});
str += '</ul></li>';
str += '</ul>';
To get the second list:
var str = '<ul>';
$.each(data.Controls[0], function(k,v) {
str += '<li>' + k + '</li>';
});
str += '</ul>';
To target them by index, so Button is 0:
var str = '<ul>';
var target = 0;
var count = 0;
$.each(data.Controls[0], function(k,v) {
if(count == target)
{
str += '<li>' + k + '<ul>';
$.each(v[0], function(kk, vv){
str += '<li>' + kk + ':' + vv + '</li>';
});
str += '</ul></li>';
return false; // <-- break because we got what we wanted
}
count++;
});
str += '</ul>';
First of all, this has nothing to do with JSON. JSON is a string-serialization format. What you have here is an object literal.
Second, I have no idea why you are wrapping all your object definitions inside Controls, with arrays, seems like a lot of extra hassle. You are also doing things in a very non-jQuery way.
You could try something like this:
var data = {
"Controls": {
"Button":{ "x": "1","y": "2","width": "3","height": "4" },
"Image":{"x": "5","y": "6","width": "7","height": "8"},
"TextField":{"x": "9","y": "10","width": "11","height": "12"}
}
}
$('div').append('<ul id="outer_ul">');
$.each(data.Controls, function(key, value) {
$('#outer_ul').append('<li>' + key + '</li>', '<ul id="' + key +'">');
$('#field_list').append('<li>' + key + '</li>');
$.each(value, function(key2, value2) {
$('#' + key).append('<li>' + key2 + ':' + value2 + '</li>');
}
}
This code populates both you div as well as a ul with the id of field_list which would represent the container into which you want to put the second list (so adjust this code according the the proper jQuery selector you want to use.

Categories

Resources