how to display data with javascript [object] [duplicate] - javascript

This question already has answers here:
How can I display a JavaScript object?
(40 answers)
Closed 3 years ago.
Please Help Me data does not appear in the div
result and display [object] how to fix it?
<div id="result">
</div>
<script>
jQuery(document).ready(function($){
var html = 'Sedang memproses data';
$('#result').html(html);
$('#result').css('background','none');
$.getJSON( "get.php?nopel=<?php echo $idp;?>", function(data) {
if(data) {
html = '<h2>Berikut Tagihan Listrik Anda</h2><table>';
$.each(data,function(x,y){
html += '<tr><td>'+x.replace('_','/')+'</td><td>'+y+'</td>';
});
html += '</table>';
$('#result').html(html);
}
else {
$('#result').html('Tidak ada data');
}
});
});
</script>
with json data like this, how to invite it to JavaScript
{
"status": "success",
"data": [
{
"Info": "A",
"hasil": "AA"
},
{
"Info": "B",
"hasil": "BB"
}
]
}
console.log (data)

Firstly, please don't use multiple accounts to ask the same question.
There are two main issues with your code...
As pointed out in comments by multiple people, if you want the dataproperty in your data json object, then you need to use data.data instead of data
The $.each function passes two parameters (index and value), but it appears that you think that it's passing the two properties of the object.
The below has the two changes, where you can see I've changed function(x,y) to function(i,v) where v is the object. I'm then using v.Info and v.hasil...
var data =
{
"status": "success",
"data": [
{
"Info": "A",
"hasil": "AA"
},
{
"Info": "B",
"hasil": "BB"
}
]
}
$(function(){
var html = 'Sedang memproses data';
$('#result').html(html);
$('#result').css('background','none');
//$.getJSON( "get.php?nopel=<?php echo $idp;?>", function(data) {
if(data) {
html = '<h2>Berikut Tagihan Listrik Anda</h2><table>';
$.each(data.data,function(i,v){
html += '<tr><td>'+v.Info.replace('_','/')+'</td><td>'+v.hasil+'</td>';
});
html += '</table>';
$('#result').html(html);
}
else {
$('#result').html('Tidak ada data');
}
//});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="result">
</div>

Related

for json Element id = "1" , append ul 'chapter_count' times

I am fairly new to web dev and This is my first question on StackOverflow. Apologies if I didn't frame it properly.
Here is my json.
{
"books":
[
{
"_id": "1",
"book_cat": "OLD",
"book_eng_name": "Book1",
"chapter_count": "50"
},
{
"_id": "2",
"book_cat": "OLD",
"book_eng_name": "Book2",
"chapter_count": "40""
}
]
I want to use this json with jquery to append to . First I need to filter __id and then append a statement to the <ul> "Chapter_count" times.
For instance, if I select I am searching for _id 1 I want 50 item list that says
Chapter 1
Chapter 2
...
...
...
Chapter 50
I want to append to ul in the following html:
<html>
<title>Chapters</title>
<body>
<ul></ul>
<script type="text/javascript"
src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/
jquery.min.js"></script>
<script type = "text/javascript" src='files/js/Chapter_script.js'></script>
<script type = "text/javascript" src='files/js/books.json'></script>
</body>
</html>
I wrote something like this but didn't work :(
(document).ready(function(){
var search_id = window.location.search;
var chapter_no = search_id.match(/\d+/g);
$.getJSON("files/js/books.json",function(data){
$.each(data.books, function(){
if (this['_id'] == chapter_no ){
for(var i = 0; i <= this['chapter_count']; i++; ){
$("ul").append("<li>Chapter Number"+i+"</li></br>")
}
};
})
});
});
Where chapter_no is extracted from url with window.location.search
Sample url: http://localhost:90/chapters.html?book_id=1
Thanks in advance.
Copy the below code in $.getJSON("files/js/books.json",function(data) function.
var selectedElement = $.grep(data.books, function( element, index ) {
if(chapter_no == element._id)
return element
});
for(var i =0 ; i<=selectedElement[0].chapter_count;i++)
{
$("ul").append("<li>Chapter Number"+i+"</li></br>")
}
first your json is not valid and have syntax error i think the true one is
json ={ "books": [ { "_id": "1", "book_cat": "OLD", "book_eng_name": "Book1",
"chapter_count": "50" }, { "_id": "2", "book_cat": "OLD",
"book_eng_name": "Book2", "chapter_count": "40" } ]}
its sample js code
json.books.forEach(function (b){
if(b._identer code here == "1")
{
for(var i =0 ; i<=b.caphter_count;i++)
{
//put your code here
}
}
})

How can I replace outer object with an array?

I'm trying to make a graph. S I need to send an ajax request, select some rows from database, then return the result. I did it. And here is the output:
success : function (data) {
console.log(data);
}
To make that graph, I need to convert my current output to this structure: (this structure is the one I should pass it to the library which draws the graph)
var json = [
{
"adjacencies": [
{
"nodeTo": "graphnode15",
"nodeFrom": "graphnode0",
"data": {}
},
{
"nodeTo": "graphnode16",
"nodeFrom": "graphnode0",
"data": {}
},
{
"nodeTo": "graphnode17",
"nodeFrom": "graphnode0",
"data": {}
}
],
"data": {
"$color": "#83548B",
"$type": "circle"
},
"id": "12",
"name": "sajad"
}
];
I've tested all of these:
console.log(data);
console.log([data]);
console.log(JSON.stringify(data));
console.log("["+JSON.stringify(data)+"]");
But none of them isn't expected structure for the library which draws the graph. Anyway, Does anybody know how can I make expected structure?
JSON.parse(data) will do this.
Try:
json =[]
json.push(data)
send this json to the graph
Maybe this should work
success : function (data) {
var json = [JSON.parse(data)];
console.log(json);
}

How to parse json object in javascript [duplicate]

This question already has answers here:
How can I access and process nested objects, arrays, or JSON?
(31 answers)
Closed 7 years ago.
How to parse following json object
{ "info": [ { "systemIp": "192.168.1.1", "status": "done 956" }, { "systemIp": "192.153.1.1", "status": "done" } ] }
In Javascript or jQuery can anybody help?
Output should be like
systemIp 192.168.1.1
status done
systemIp 192.153.1.1
status done
Use this
<script type="text/javascript">
var abc = { "info": [ { "systemIp": "192.168.1.1", "status": "done 956" }, { "systemIp": "192.153.1.1", "status": "done" } ] };
$.each(abc.info,function(i,val){
alert("systemIp : "+val.systemIp);
alert("status : " +val.status);
});
/* other way ot iterate */
$.each(abc.info,function(i,outer){
$.each(outer,function(j,inner){
alert(j+" : "+inner);
});
});
</script>
This is not very efficient way, but this will serve your purpose
var a ={ "info": [ { "systemIp": "192.168.1.1", "status": "done 956" },
{ "systemIp": "192.153.1.1", "status": "done" } ] }
var objL = a['info']
for(var i = 0;i<objL.length;i++){
for(keys in objL[i]){
console.log( keys + ' ' +objL[i][keys])
}
}
Example
With JavaScript: JSON.parse()
With jQuery: jQuery.parseJSON()

Mixed array with json - parsing issue

I am doing a youtube api call, and I get back a var result = JSON.stringify(response, '', 2); which looks like :
{
"kind": "youtube#searchListResponse",
"pageInfo": {
"totalResults": 1000000,
"resultsPerPage": 5
},
"items": [
{
"id": {
"kind": "youtube#video",
"videoId": "DEne4AoX_RU"
},
"kind": "youtube#searchResult",
"snippet": {
"publishedAt": "2012-11-22T22:36:15.000Z",
"thumbnails": {
"default": {
"url": "https://i.ytimg.com/vi/DEne4AoX_RU/default.jpg"
},
"medium": {
"url": "https://i.ytimg.com/vi/DEne4AoX_RU/mqdefault.jpg"
},
"high": {
"url": "https://i.ytimg.com/vi/DEne4AoX_RU/hqdefault.jpg"
}
}
}
},
{
"id": {...}
The full object response returns correctly in my console but I want to retrieve thumbnails url and display it as an li-tagged html list
So I tried first to fetch in a list all the snippet entries :
var obj = $.parseJSON(result);
$.each(obj, function() {
output += this.snippet + + "<br/>";
});
console.log(output);
But I have an message in my console : Uncaught TypeError: Cannot read property 'length' of undefined. What am I missing ? Btw, I don't understand why there are still brackets in the json stringified result (if someone could advise some good doc to understand how to parse JSON, would be great:))
You should be looping over items:
$.each(obj.items, function() {
output += this.snippet ...
});
What you receive is JSON, you shouldn't stringify it.
Remove this line
var result = JSON.stringify(response, '', 2);
and simply do
var obj = $.parseJSON(response);
you want to iterate over items,
snippet is an object literal,
+ + is not valid javascript.

how to use for each with mustache javascript?

i have some json objects and some of them have some other objects inside them.
if i leave only the json obj that don't have other obj inside them and then apply the template, everything goes well, i get, in this case 3 li elements.
but if i grab the original json obj the results are a bit wired. I believe i need to do a each statement to iterate through each sub json obj from inside each main one
maybe i am a bit confuse so here is some code.
i have some json data like this:
{
"msg_id":"134",
"message":"Nick",
"comment":[
{
"com_id":"9",
"comment":"test",
},
{
"com_id":"10",
"comment":"testtt",
},
{
"com_id":"11",
"comment":"testtttt",
}]
},
{
"msg_id":"134",
"message":"Nick",
},
{
"msg_id":"134",
"message":"Nick",
}
and i am trying to arive at something like this:
Nick
test
testtt
testtttt
Nick
Nick
i've created a template like this:
function messagesTamplate(data)
{
$.each(data, function(index, obj)
{
msg += template.replace( /{{message}}/ig , obj.message );
if(obj.comment) {
$.each(obj.comment, function(key, val)
{
msg += template.replace( /{{comment}}/ig , val.comment );
});
}
});
return msg;
}
then i just append this to the main ul.
thanks
data needs to be an array (see the enclosing [])
var data = [{
"msg_id": "134",
"message": "Nick",
"comment": [{
"com_id": "9",
"comment": "test",
}, {
"com_id": "10",
"comment": "testtt",
}, {
"com_id": "11",
"comment": "testtttt",
}]
}, {
"msg_id": "134",
"message": "Nick",
}, {
"msg_id": "134",
"message": "Nick",
}]
is just this in mustache templates:
{{#data}} //loop through all data
{{message}} //pick out the "message" per iteration
{{#comment}} //loop through all comments in an iterated item
{{comment}} //pick out the comment
{{/comment}}
{{/data}}

Categories

Resources