Populating dynamic table with json data - javascript

<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<title>MongoDB Display</title>
<script>
$(document).ready(function(){
var Obj = $.getJSON("http://localhost:3000", function(){
alert("Success");
$(Obj.rows).each(function(index, element){
$(#tableID).append('<tr><td>' + element[1] + '</td><td><table><tr><td>'+ Obj.rows.scripts.element[0]
+ '</td>' + "/" + '<td>' + Obj.rows.scripts.element[1] + '</td></tr></table></td></tr>');
})
});
});
</script>
</head>
<body>
<div id="wrapper">
<h1>H 1</h1>
<table id="tableID" border = "1">
<th>
<td>PAGE</td>
<td>SCRIPTS</td>
</th>
</table>
</div>
</body>
</html>
In short;
I have a MongoDB ready to be displayed at localhost:3000. Server is running and I can display the data on the browser with localhost:3000 But when i try to run the above code on the browser, all i can get the js Alert("Success") and the hard coded part of the table. PAGE and SCRIPTS...
the data is:
{
"offset": 0,
"rows": [
{
"_id": {},
"url": "http://www.qweq.com\r",
"totalLines": 3084,
"scripts": [
{
"line": 111,
"tag": "\"asdas/etc/designs/qwe/assets/head-5.30.31.min.js\""
},{
"line": 3065,
"tag": "\"asdas/etc/designs/qwe/assets/common-5.30.31.min.js\""
},{
"line": 3067,
"tag": "\"asda/etc/designs/qwe/assets/category-5.30.31.min.js\""
}
]
},{
"_id": {},
"url": "http://www.qweqsd.com/qwdq23/qweq/qweqw/\r",
"totalLines": 3042,
"scripts": [
{
"line": 113,
"tag": "\"asda/etc/designs/asd/assets/head-5.30.31.min.js\""
},{
"line": 3023,
"tag": "\"asdasd/etc/designs/asd/assets/common-5.30.31.min.js\""
},{
"line": 3025,
"tag": "\"asdad/etc/designs/qwe/assets/category-5.30.31.min.js\""
}
]
},
How can I make this Json data to be display in a dynamic table?
Thank you.

This version is kind of working :) Maybe you'll find inspiration.
$(rows).each(function(index,element){
console.log(index); console.log(element);
$('#tableID').append('<tr><td>' + index + '</td><td>'+ element['url']
+ '</td>' + "/" + '<td>' + JSON.stringify(element['scripts']) + '</td></tr></table>');
});
http://jsfiddle.net/fw4f5L72/1/

It looks like you're missing quotes around the table name. Instead, you should have something like $('#tableID').
Additionally, you'll want your function call to include the data that it's returning to you. For example:
$.getJSON("http://localhost:3000", function(data){
alert("Success");
console.log(data);
});
Then, data will include the JSON object, and you can manipulate it however you please.

Related

How to render local json file into HTML and browser

I am pretty new in Javascript and I have problem. Currently I am working on project, that is actually my practice project and I'm trying to make shopping cart page. My problem is with JSON file, I don't know how to render it (show it within HTML in browser), I have local JSON file with some products. Here is my code of main page, app.js(where is my function for JSON file) and JSON file with products
HTML file
<!DOCTYPE html>
<html lang="en">
<head>
<title>Shopping Cart</title>
<meta charset="utf-8" />
<meta name="description" content="cobe" />
<meta name="author" content="cobe" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<link rel="stylesheet" href="../style/style.css" />
</head>
<body>
<main class="main-wrapper">
<div class="items">
<div class="item">
<div class="image">
<img src="" alt="" class="img">Image</img>
</div>
<h2 class="item-name">Name of item</h2>
<h3 class="price">Price</h3>
<button class="button">Add item</button>
</div>
<div id="products" class="list"></div>
</div>
</main>
<script type="text/javascript" src="../products.json"></script>
<script type="text/javascript" src="../app.js"></script>
app.js file
let xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
let response = JSON.parse(xhttp.responseText);
let products = response.products;
let output = '';
for (let i = 0; i < products.length; i++) {
output += '<li>' + products[i].name + '</li>';
}
document.getElementById('products').innerHTML = output;
}
};
xhttp.open("GET", "products.json", true);
xhttp.send();
and JSON file which is called products.json
{
"products": [
{
"id": 1,
"name": "Eggs",
"image": "https://d17zv3ray5yxvp.cloudfront.net/variants/W1ymDizfe679XsfX9uP8A5bU/7b27a910a7194c812eacf34700e38dcab3abed02f30837d1dad313c5651bb5fa",
"price": {
"amount": 7.99,
"currency": "Kn",
"measureUnit": "Kom"
}
},
{
"id": 2,
"image": "https://d17zv3ray5yxvp.cloudfront.net/variants/b1qEMnNGbwiwV5cWysofPoqz/7b27a910a7194c812eacf34700e38dcab3abed02f30837d1dad313c5651bb5fa",
"name": "Milk",
"price": {
"amount": 4.99,
"currency": "Kn",
"measureUnit": "Kom"
}
},
{
"id": 3,
"image": "https://d17zv3ray5yxvp.cloudfront.net/variants/1avpwnxKAEqEpTf1k3VCbBbg/7b27a910a7194c812eacf34700e38dcab3abed02f30837d1dad313c5651bb5fa",
"name": "Cheese",
"price": {
"amount": 44.99,
"currency": "Kn",
"measureUnit": "Kg"
}
}
]
}
So my question is what should I write in HTML file so I could get let's say name of product from JSON file into my div which is declared in HTML file for name or am I missing some more JS functions? Currently my page is blank because I couldn't resolve how to get everything from JSON file.
HTML files are in views folder, app.js and products.json are outside of views folder.
Thanks!
Try using a function to generate the template and set the innerHTML property.
You can use this populateProducts function once you have got the response JSON from the API. This will generate the template and will update the DOM.
var myData = {
"products": [
{
"id": 1,
"name": "Eggs",
"image": "https://d17zv3ray5yxvp.cloudfront.net/variants/W1ymDizfe679XsfX9uP8A5bU/7b27a910a7194c812eacf34700e38dcab3abed02f30837d1dad313c5651bb5fa",
"price": {
"amount": 7.99,
"currency": "Kn",
"measureUnit": "Kom"
}
},
{
"id": 2,
"image": "https://d17zv3ray5yxvp.cloudfront.net/variants/b1qEMnNGbwiwV5cWysofPoqz/7b27a910a7194c812eacf34700e38dcab3abed02f30837d1dad313c5651bb5fa",
"name": "Milk",
"price": {
"amount": 4.99,
"currency": "Kn",
"measureUnit": "Kom"
}
},
{
"id": 3,
"image": "https://d17zv3ray5yxvp.cloudfront.net/variants/1avpwnxKAEqEpTf1k3VCbBbg/7b27a910a7194c812eacf34700e38dcab3abed02f30837d1dad313c5651bb5fa",
"name": "Cheese",
"price": {
"amount": 44.99,
"currency": "Kn",
"measureUnit": "Kg"
}
}
]
};
function populateProducts() {
var template = '';
for(let index = 0; index < myData.products.length; index++) {
template +=
"<div>Name: " + myData.products[index].name + "</div>" +
"<div>Image: <img class='my-image' src='" + myData.products[index].image + "' /></div>"+
"<div>Amount: " + myData.products[index].price.amount + "</div>" +
"<div>Currency: " + myData.products[index].price.currency + "</div>" +
"<div>MeasureUnit: " + myData.products[index].price.measureUnit + "</div>";
}
document.getElementById('item-wrapper').innerHTML = template;
}
populateProducts();
.my-image {
max-width: 50px;
}
<main class="main-wrapper">
<div id="item-wrapper"></div>
</main>
If you're able to use a templating system such as Handlebars.js, you could convert the repeated part of your HTML (the item div) into a template and then populate it with the data. Adapting the 'Getting Started' example from the Handlebars page, the template would look something like:
<script id="item-template" type="text/x-handlebars-template">
{{#each products}}
<div class="item">
<div class="image">
<img src="{{image}}" alt="" class="img">Image</img>
</div>
<h2 class="item-name">{{name}}</h2>
<h3 class="price">{{price.amount}}</h3>
<button class="button">Add item</button>
</div>
{{/each}}
</script>
Then in the script you would register the template:
const source = document.getElementById("item-template").innerHTML;
const template = Handlebars.compile(source);
...and then inside your HTTP request, you can pass the data to the template and it'll return HTML which you can add to the DOM as you wish:
const html = template(context);

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

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>

How to use single json file to consume in alpacajs

I have created a simple form using alpacajs, as per the documentation provided by alpacajs.org we can use properties such as optionsSource, schemaSource, viewSource, dataSource for loading the external json files into our application. But what i need is i need to use only one json file for all these. I mean instead of using all these 3 different properties can i use only one parameter for loading the single json file which comes from the backend. please check my code below..
<html>
<head>
<meta charset="UTF-8">
<title>My Little Alpaca Form</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/handlebars.js/4.0.5/handlebars.min.js"> </script>
<script src="https://code.jquery.com/jquery-1.12.4.min.js" integrity="sha256-ZosEbRLbNQzLpnKIkEdrPv7lOy9C27hHQ+Xp8a4MxAQ=" crossorigin="anonymous"></script>
<script src="//code.cloudcms.com/alpaca/1.5.22/bootstrap/alpaca.min.js"></script>
<!-- typeahead.js https://github.com/twitter/typeahead.js -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/typeahead.js/0.10.5/bloodhound.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/typeahead.js/0.10.5/typeahead.bundle.min.js"></script>
<link href="//code.cloudcms.com/alpaca/1.5.22/bootstrap/alpaca.min.css" rel="stylesheet" />
<link type="text/css" href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap.min.css" rel="stylesheet"/>
</head>
<body>
<div id="form1"></div>
<script type="text/javascript">
$(document).ready(function() {
$("#form1").alpaca({
"dataSource": "/fulfiller/connector-custom-data.json",
"schemaSource": "/fulfiller/connector-custom-schema.json",
"optionsSource": "/fulfiller/connector-custom-options.json",
"viewSource": "/fulfiller/connector-custom-view.json",
"view": {
"parent": "bootstrap-edit",
"layout": {
"template": "threeColumnGridLayout",
"bindings": {
"requestedfor": "column-1",
"location": "column-2",
"shortdescription": "column-3",
"description": "column-3",
}
},
"templates": {
"threeColumnGridLayout": '<div class="row">' + '{{#if options.label}}<h2>{{options.label}}</h2><span></span>{{/if}}' + '{{#if options.helper}}<p>{{options.helper}}</p>{{/if}}' + '<div id="column-1" class="col-md-6"> </div>' + '<div id="column-2" class="col-md-6"> </div>' + '<div id="column-3" class="col-md-12"> </div>' + '<div class="clear"></div>' + '</div>'
}
},
"options": {
"fields": {
"requestedfor": {
"type": "text",
"id": "requestedfor",
"label": "*Requested For",
"typeahead": {
"config": {},
"datasets": {
"type": "remote",
"displayKey": "value",
"templates": {},
"source": "http://www.alpacajs.org/data/tokenfield-ajax1.json"
}
}
},
"location": {
"type": "text",
"label": "*Location"
},
"shortdescription": {
"type": "text",
"label": "Short Description"
},
"description": {
"type": "textarea",
"rows": 5,
"cols": 40,
"label": "Description"
}
},
"form": {
"attributes": {
"action": "#",
"method": "post"
},
"buttons": {
"submit": {
"value": "Submit",
"class": "btn btn-default"
}
}
}
}
});
});
</script>
</body>
</html>
So here in the above code i have used these urls for loading json data..
"dataSource": "/fulfiller/connector-custom-data.json"
"schemaSource": "/fulfiller/connector-custom-schema.json"
"optionsSource": "/fulfiller/connector-custom-options.json"
"viewSource": "/fulfiller/connector-custom-view.json"
So instead of using these 3 different properties can i use only one property like "oneSingleJSONSource": "oneJSONRemoteFile.json"
Can anybody provide inputs?
For Alpaca to be inialized it must have a DOM element + a config object that contains the schema, options and other properties that Alpaca already knew in its core code, so in your case this is possible if you try to modify the alpaca core code... If your objective is only to optimize resource loading you can use only one json file that contains all the configuration and input them in the alpaca initialization $(dom).alpaca(_json_data_from_loaded_file). And if you want to have only schema, options and view settings in on file you should divide the data loaded to 3 objects, 1 for schema, 1 for options and the last one for view settings.
Tell me if you want more details on achieving this.
I'll be glad to help.

How do I format the display of a select from properties of the objects using angular?

$scope.StateList = {"States": [
{
"Id": 1,
"Code": "AL",
"Name": "Alabama"
},
{
"Id": 2,
"Code": "AK",
"Name": "Alaska"
},
{
"Id": 3,
"Code": "AZ",
"Name": "Arizona"
},
{
"Id": 4,
"Code": "AR",
"Name": "Arkansas"
}]}
And I display the data as follows in an html select:
<select ng-model="Address.State"
ng-options="state.Code as state.Name for state in StateList.States"></select>
Right now this will display the full name of the state in the select like "Arizona". What I would like to do is format the display without adding a new property to the object, to use something like (state.Name, state.Code, state.Id). I am trying to use filters of some sort to do this but I have not figured it out yet. Thanks for your suggestions.
plunker
There are three ways that you can achieve this. The first is to just set the value you want inline:
<select ng-model="Address.State" ng-options="state.Code as (state.Name + ', ' + state.Code + ', ' + state.Id) for state in StateList.States"></select>
Or you can do the same thing, but as a function in your controller:
$scope.display = function(state) {
return state.Name + ', ' + state.Code + ', ' + state.Id;
}
<select ng-model="Address.State" ng-options="state.Code as display(state) for state in StateList.States"></select>
Or you can create a filter (as per PSLs answer)
Try creating a small format filter:-
app.filter('stateName', function() {
return function(itm) {
return [itm.Name , itm.Code, itm.Id].join();
}});
and use it as:-
ng-options="state.Code as (state|stateName) for state in StateList.States
Plnkr

JSON data won't be displayed via jQuerys getJSON()

The following code should display the id out of the JSON-object, which I got from a server. I cant find the mistake, could somebody help me? Thank you in advance!
The JSON-object which is returned when http://localhost:8387/nscalemc/rest/mon/resourcestatus.json is called:
{
"groupStatus": [
{
"id": "Application Layer Configuration-ApplicationLayer",
"time": 1332755316976,
"level": 0,
"warningIds": [],
"errorIds": []
},
{
"id": "Application Layer-ApplicationLayer:nscalealinst2",
"time": 1333431531046,
"level": 0,
"warningIds": [],
"errorIds": []
},
{
"id": "Application Layer-ApplicationLayer:nscalealinst1",
"time": 1333431531046,
"level": 1,
"warningIds": [
"documentarea.locked"
],
"errorIds": []
},
{
"id": "Storage Layer-StorageLayerInstance1",
"time": 1331208543687,
"level": 0,
"warningIds": [],
"errorIds": []
}
]
}
My HTML file gadget.html:
<html>
<head>
<title>Monitor</title>
<link href="css/gadget.css" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="js/jquery-1.7.2.js"></script>
<script type="text/javascript" src="js/gadget.js"></script>
</head>
<body>
<div id="content"></div>
</body>
</html>
My JavaScript file "gadget.js":
fetch_JSON();
function fetch_JSON() {
var url = "http://localhost:8387/nscalemc/rest/mon/resourcestatus.json";
$.getJSON(url+'?callback=?', function(data) {
$(data.groupStatus).each(function() {
$('#content').append('<p>ID: ' + $(this).id+ '</p>');
});
});
}
EDIT:
Thank you for your solutions! I debugged via Firebug and found out, that the getJSON-call ends with status "401 unauthorized"..
You should do
$('#content').append('<p>ID: ' + this.id+ '</p>');
fiddle here http://jsfiddle.net/JaxpC/
EDIT - of course you should use the ready handler to make sure thatthe dom is present (i don't think that's your case because there i an ajax call involved, but better be sure
$(function() {
var url = "http://localhost:8387/nscalemc/rest/mon/resourcestatus.json";
$.getJSON(url+'?callback=?', function(data) {
$(data.groupStatus).each(function() {
$('#content').append('<p>ID: ' + this.id+ '</p>');
});
});
});
You are running the script immediately and have placed it before the div. #content doesn't exist when you try to append data to it.
Move the script to just before </body>.
$(document).ready(function(){
fetch_JSON();
function fetch_JSON() {
var url = "http://localhost:8387/nscalemc/rest/mon/resourcestatus.json";
$.getJSON(url+'?callback=?', function(data) {
$(data.groupStatus).each(function() {
$('#content').append('<p>ID: ' + this.id+ '</p>');
});
});
}
});

Categories

Resources