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

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>');
});
});
}
});

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 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.

Trouble with accessing object in JSON array

I can't seem to figure out how to get this code snippet to work. I am trying to access the 'Name' object in this json snippet. Any help would be appreciated.
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js">
</script>
<script>
$(document).ready(function () {
$.getJSON('https://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20yahoo.finance.quotes%20where%20symbol%20in%20(%22AAPL%22)&format=json&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys&callback=', function(data) {
$('#demo').text(data[0].Name);
});
});
</script>
</head>
<body>
<p id="demo"></p>
</body>
</html>
Use this:
$(document).ready(function () {
$.getJSON('https://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20yahoo.finance.quotes%20where%20symbol%20in%20(%22AAPL%22)&format=json&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys&callback=', function(data) {
$('#demo').text(data.query.results.quote.Name);
});
});
{
"query": {
"count": 1,
"created": "2017-02-13T18:34:48Z",
"lang": "es-419",
"results": {
"quote": {
"name": "Blabla"
So you have data.query.results.quote.name
Your API call does not return an array, it returns a JSON object.
Try: $('#demo').text(data.query.results.quote.Name);
Here's what the data structure that is being returned looks like:
{
"query": {
"count": 1,
"created": "2017-02-13T18:34:12Z",
"lang": "en-us",
"results": {
"quote": {
// other props...
"Name": "Apple Inc.",
// other props...
}
}
}
}

Passing Json data from Controller to View in Angular JS to build a table

Trying to get the certain fields to display, ideally in a table (headings, rows & columns). And looking for a best way find fields in a Json feed. I tried using the controller to find the fields then pass that data to the view in the HTML.
Is there something wrong in the controller with respect to the Json? the fields are empty. Seems like nothing is passed from the controller to the view ? This is what I tried:
<!doctype html>
<html ng-app="app" >
<head>
<meta charset="utf-8">
<title>LIVE</title>
<!-- <link rel="stylesheet" href="style.css"> -->
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.js"></script>
<script>
var app = angular.module('app', []);
app.controller('DataCtrl', function ($scope, $http) {
$scope.result = {
"data": {
"transactionList": [{
"barcode": "52905819992681",
"training": 0,
"tranNo": 1,
"userId": "8796093054980",
"retailerId": "defaultRetailer",
"storeId": "12Store",
"deviceId": "afd03463-9ee7-45d4-9d2e-8d64a683f126",
"tillId": "2",
"tranTypeId": "regularSale",
"isTranVoid": 0,
"totalItems": 1,
"merchTotal": 50.0,
"promoTotal": 0.0
}, {
"barcode": "52905819592681",
"training": 0,
"tranNo": 1,
"userId": "8796093054980",
"retailerId": "defaultRetailer",
"storeId": "23Store",
"deviceId": "afd03463-9ee7-45d4-9d2e-8d64a683f126",
"tillId": "2",
"tranTypeId": "regularSale",
"isTranVoid": 0,
"totalItems": 1,
"merchTotal": 50.0,
"promoTotal": 0.0
}]
}
}
};
$scope.elements = $scope.result.data.transactionList.map(function (res) {
var e = {};
e.transTypeId = res.transTypeId;
e.userId = res.userId;
e.storeId = res.storeId;
return e;
});
});
</script>
</head>
<body ng-controller="DataCtrl">
<h1>Live from the JSON feed</h1>
<ul>
<li ng-repeat="e in elements">
{{ e.transTypeId}}: {{ e.userId }}, {{ e.storeId }}
</li>
</ul>
</body>
</html>
You have a extra } in your $scope.result. It should be like:
$scope.result = {
"data": {
"transactionList": [{
"barcode": "52905819992681",
"training": 0,
"tranNo": 1,
"userId": "8796093054980",
"retailerId": "defaultRetailer",
"storeId": "12Store",
"deviceId": "afd03463-9ee7-45d4-9d2e-8d64a683f126",
"tillId": "2",
"tranTypeId": "regularSale",
"isTranVoid": 0,
"totalItems": 1,
"merchTotal": 50.0,
"promoTotal": 0.0
}, {
"barcode": "52905819592681",
"training": 0,
"tranNo": 1,
"userId": "8796093054980",
"retailerId": "defaultRetailer",
"storeId": "23Store",
"deviceId": "afd03463-9ee7-45d4-9d2e-8d64a683f126",
"tillId": "2",
"tranTypeId": "regularSale",
"isTranVoid": 0,
"totalItems": 1,
"merchTotal": 50.0,
"promoTotal": 0.0
}]
}
};
// get rid of this};
Here is working plunkr
Perhaps a }; too many?
Automatic indentation usually makes those kinds of errors apparent.
Have you tried to use ng-model="...", it gives you the opportunity to overwrite an attribute or to show it. You can try it with
<input type="number" ng-model="someID" disabled="disabled">
*disabled if u need readOnly on that field.
and see how it works, maybe it can help you out.
regards
I may be wrong, but you are trying to read json data directly without parsing it?
MDN JSON.parse()
Also it would be nice if you upload your code on something like http://jsfiddle.net
This way people can test it out.

Populating dynamic table with json data

<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.

Categories

Resources