I am trying to read the json data from a static json file that I have for testing on a local web server but I cannot get anything to show up with using the $http.get() service. I looked at a few other similar questions here but all accepted answers account for use of the promise methods, however on the angularjs v1.6.x+ these have been depreciated.
Initially I tried setting my json data on a variable inside of the controller, and everything worked fine, however once I moved to a JSON file nothing shows up. My first error was that I was unaware the JSON file has to be in ANSI format for the JSON.parse() angular calls to be able to work. Before switching the file encoding to ANSI I was getting syntax errors and my json structure was correct. (some text editor like Dreamweaver will create JSON files in UTF-8 format).
At this point when I inspect the webpage there are no JS errors on the console whatsoever, however no data shows up at all. Here is what I have:
My events.json
[
{
"day" : "Monday",
"objective" : "Pipeline",
"sessions" : [
{
"title" : "Leadership Excellence Luncheon",
"start" : "11:30am",
"end" : "1:00pm",
"location": "room A"
},
{
"title" : "Veteran Resume Workshop",
"start" : "1:15pm",
"end" : "2:00pm",
"location": "room B",
"speakers" : [
{
"name": "John Doe",
"title": "Analyst",
"company": "Appel",
"headshot" : "http://placehold.it/119x134.jpg",
"bio": "john-doe/",
},
{
"name": "Jane Doe",
"title" : "VP",
"company": "Lancer",
"headshot" : "http://placehold.it/119x134.jpg",
}
]
}
]
},
{
"day" : "Tuesday",
"objective" : "Pipeline",
"sessions" : [
{
"title" : "Leadership Excellence Luncheon",
"start" : "11:30am",
"end" : "1:00pm",
"location": "room A"
},
{
"title" : "Veteran Resume Workshop",
"start" : "1:15pm",
"end" : "2:00pm",
"location": "room B",
"speakers" : [
{
"name": "John Doe",
"title": "Analyst",
"company": "Appel",
"headshot" : "http://placehold.it/119x134.jpg",
"bio": "john-doe/",
},
{
"name": "Jane Doe",
"title" : "VP",
"company": "Lancer",
"headshot" : "http://placehold.it/119x134.jpg",
}
]
}
]
}
}
Here is my app.js
(function() {
var app = angular.module('Agendas',[]);
app.controller('TableController', ['$scope', '$http',
function($scope,$http) {
$scope.title = "test";
$scope.events = [];
$http({
method: 'POST',
url: 'http://localhost/ang/data/events.json',
}).then( function(response) {
$scope.events = response;
});
}]);
})();
Here is my index.html
<!doctype html>
<html>
<head>
.....
</head>
<body>
....
<div id="agenda" class="mainCont container-fluid well" ng-app="Agendas" ng-controller="TableController">
<div id="day" ng-repeat="event in events">
<h1>{{ event.day }} — {{ event.objective }}</h1>
<div id="sess" ng-repeat="session in event.sessions">
<div style="width: 140px; float: left; clear: left;">{{ session.start }} - {{ session.end }}<br><br><em>Location: {{ session.location }}</em></div> <div style="float: left;"><em>{{ session.title }}</em> <br>
<div class="panelist" ng-repeat="speaker in session.speakers"><img ng-src="{{ speaker.headshot }}"><br>
<a ng-href="{{ speaker.bio }}">{{ speaker.name }}</a><br>
{{ speaker.title }} <br>
{{ speaker.company }}</div>
</div>
</div>
<div class="aghr"></div>
</div>
<script type="text/javascript" src="js/angular.min.js"></script>
<script type="text/javascript" src="js/app.js"></script>
</body>
</html>
I noticed that your JSON file contains some errors. It could be related.
The ending tag should be one to close the array. ]instead of }.
The last field of a JSON object should not have a comma. E.g.:
{
"name": "John Doe",
"title": "Analyst",
"company": "Appel",
"headshot" : "http://placehold.it/119x134.jpg",
"bio": "john-doe/", <--- remove comma
}
You can use a website as jsonlint to validate your JSON.
** As suggested, you might have to clear the browser cache first.
** Additionally change
$scope.events = response;
to
$scope.events = response.data;
Related
So I am trying to use the orderby function of angularjs. Currently I have an original data set.
$scope.customers = [
{"name" : "Bottom-Dollar Marketse" ,"city" : "Tsawassen"},
{"name" : "Alfreds Futterkiste", "city" : "Berlin"},
{"name" : "Bon app", "city" : "Marseille"},
{"name" : "Cactus Comidas para llevar", "city" : "Buenos Aires"},
{"name" : "Bolido Comidas preparadas", "city" : "Madrid"},
{"name" : "Around the Horn", "city" : "London"},
{"name" : "B's Beverages", "city" : "London"}
];
$scope.reverse= false;
$scope.toggleOrder = function(){
$scope.reverse=!$scope.reverse;
}
If I use the following to display my customers, I would get the array reverse ordered by the city. Currently I could click on the toggle button and reverse the array if wanted to.
<button ng-click="toggleOrder()">ToggleReverse</button >
<li ng-repeat="x in customers | orderBy : 'city': reverse">{{x.name + ", " + x.city}}</li>
But now the issue is if I didn't want the orderBy function at all. If I wanted to get my original customers data without any order how could I do that with the same toggleOrder function?
For instance, When I load the data it would be the original array. If 1st click of the toggleOrder button, it would sort in based on city, 2nd click of the toggleOrder button would reverse sort the city, and third click of the toggleOrder button would have no sort and give me the original array, and so on.
If the orderBy function isn't the best to go by let me know.
Any help would be great!
I'm not sure why you want to add this feature on your application, but here you go:
(function() {
'use strict';
angular
.module('app', [])
.constant('BUTTON_VALUES', {
1: 'Ascending',
2: 'Descending',
3: 'No order',
})
.controller('MainCtrl', MainCtrl);
MainCtrl.$inject = ['$scope', 'BUTTON_VALUES'];
function MainCtrl($scope, BUTTON_VALUES) {
$scope.customers = [
{
"name": "Bottom-Dollar Marketse",
"city": "Tsawassen"
},
{
"name": "Alfreds Futterkiste",
"city": "Berlin"
},
{
"name": "Bon app",
"city": "Marseille"
},
{
"name": "Cactus Comidas para llevar",
"city": "Buenos Aires"
},
{
"name": "Bolido Comidas preparadas",
"city": "Madrid"
},
{
"name": "Around the Horn",
"city": "London"
},
{
"name": "B's Beverages",
"city": "London"
}
];
$scope.btnValue = BUTTON_VALUES[3];
$scope.reverse = true;
$scope.orderParam = '';
var increment = 0;
$scope.toggleOrder = function() {
increment++;
$scope.btnValue = BUTTON_VALUES[increment];
switch (increment) {
case 1:
case 2:
$scope.orderParam = 'city';
$scope.reverse = !$scope.reverse;
break;
case 3:
$scope.orderParam = '';
increment = 0;
break;
}
}
}
})();
<!DOCTYPE html>
<html ng-app="app">
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.8/angular.min.js"></script>
</head>
<body ng-controller="MainCtrl">
<button ng-click="toggleOrder()">{{btnValue}}</button>
<pre ng-bind-template="Order - {{orderParam}}"></pre>
<pre ng-bind-template="Reverse? {{reverse}}"></pre>
<hr>
<li ng-repeat="x in customers | orderBy : orderParam: orderParam && reverse">{{x.name + ", " + x.city}}</li>
</body>
</html>
Note: I added a constant as an example to demonstrate how you can handle your button name.
I hope it helps.
So, you want the original order the third time you click on the order by button. Seems doable but complicated. Maybe instead you should have another button that is labeled "original order" and a hidden column that lists the index of your original order. Pushing that button orders by that original index.
/edited I rather use another approach of angualrjs filters which is basically taking string as param and matching it to the object in list.
jsfiddle.net/2q14sryb
Hope it works!
Right now I have this json structure
"administration" : [
{
"name" : "Sigfried Bermudez",
"role" : "Associate Director"
},
{
"name" : "Karen Madrigal",
"role" : "QA Manager"
},
{
"name" : "Jorge Lopez",
"role" : "Project Manager"
}
]
as you see the last element in that array says "role" : "Project Manager", and the way I am excluding this element from the view is this
{{#each chart-container.[3].administration}}
{{#unless #last}}
<span>{{#key}} {{this.name}}</span>
{{/unless}}
{{/each}}
but what about that element changes the position?
what I need to know is if I can do something like {{#unless this.role.toLowerCase().indexof("project")}} or what is the best option in this case? if there is a way to do this from the HTML, it would be awesome :)
Working example: JsFiddle
Use Handlebars helper:
var entry_template = document.getElementById('entry-template').innerHTML;
var data = [
{
"name" : "Sigfried Bermudez",
"role" : "Associate Director"
},
{
"name" : "Karen Madrigal",
"role" : "QA Manager"
},
{
"name" : "Jorge Lopez",
"role" : "Project Manager"
}
]
Handlebars.registerHelper("ifvalue", function(conditional, options) {
if (conditional !== options.hash.notequals) {
return options.fn(this);
} else {
return options.inverse(this);
}
});
var template = Handlebars.compile(entry_template);
var template_with_data = template(data);
document.getElementById('data').insertAdjacentHTML('afterbegin', template_with_data);
Template:
<script id="entry-template" type="text/x-handlebars-template">
{{#each this}}
{{#ifvalue this.role notequals="Project Manager"}}
{{this.name}}
{{/ifvalue}}
{{/each}}
</script>
<div id="data">
</div>
I need to view JSON in my html page as formatted view. JSON come from database. I need to show it nut in Formatted view.
Just like
{
"crews": [{
"items": [
{
"year" : "2013",
"boat" : "Blue",
"position" : "1",
"name" : "Patrick Close",
"college" : "Pembroke",
"weight" : "14st 2lbs"
}, {
"year" : "2013",
"boat" : "Blue",
"position" : "2",
"name" : "Geordie Macleod",
"college" : "Christ Church",
"weight" : "13st 10lbs"
}]
}]
}
Anyone have any idea or suggestion ? or any resource that may help.
Edited: I want to create a JSON parser. User input different json and can view in formatted view.
Try JSON.stringify(data), its a Javascript function. Hope it might help.
Refer: Detail Explaination
If you are using PHP then use json_encode
Refer: json_encode manual
Since your are using angular-js, you can simply load your JSON feed from your controller then use the ng-repeat function to iterate over the items into your view page. Here down a sample where of how your HTML view can look like and you may need to style and build the blocks as per your needs:
<span>items:</span>
<span>[</span>
<br/>
<div class="item" ng-repeat="item in items">
<span>{</span><br/>
<span class="field">year : {{item.year}}</span><br/>
<span class="field">boat : {{item.boat}}</span><br/>
<span class="field">position : {{item.position}}</span><br/>
<span>}</span>
</div>
You can find a working sample in this JSFiddle.
First: your remote JSON is invalid: it's missing an ending bracket for crews.
It should be like this:
{
"crews": [{
"items": [
{
"year" : "2013",
"boat" : "Blue",
"position" : "1",
"name" : "Patrick Close",
"college" : "Pembroke",
"weight" : "14st 2lbs"
}, {
"year" : "2013",
"boat" : "Blue",
"position" : "2",
"name" : "Geordie Macleod",
"college" : "Christ Church",
"weight" : "13st 10lbs"
}]
}] // Missing this bracket
}
You didn't mention if your JSON is remote or not. I'm assuming not, so I'll use a local JavaScript var with eval function in this sample code.
<script type="text/javascript">
var content = {
"crews": [{
"items": [
{
"year" : "2013",
"boat" : "Blue",
"position" : "1",
"name" : "Patrick Close",
"college" : "Pembroke",
"weight" : "14st 2lbs"
}, {
"year" : "2013",
"boat" : "Blue",
"position" : "2",
"name" : "Geordie Macleod",
"college" : "Christ Church",
"weight" : "13st 10lbs"
}]
}]
};
var json = eval(content);
for (c in json.crews) {
var crew = json.crews[c];
for (i in crew.items) {
var item = crew.items[i];
console.log(item.year);
console.log(item.boat);
console.log(item.position);
console.log(item.name);
}
}
</script>
I'm using console.log to output, so you'll be able to see data only if you open the browser console:
I'm new in angularjs,i'm trying to load data from my json file on view. json file have some list of patients.
But does not get showed on my view
here is my 'patient.json' file
[
{
"id": 0,
"first_name": "John",
"last_name": "Abruzzi",
"middle_name": "Kewan",
"DOB": "12/03/1935",
"ssn": "254-2342-42",
"sex" : "Male",
"country" : "USA",
"city" : "Greater New York",
"phone" : "1234124822",
"military_branch" : "Army",
"zip" : "08675",
"guid" : ""
},
{
"id": 1,
"first_name": "Peter",
"last_name": "Burk",
"middle_name": "S",
"DOB": "31/06/1945",
"ssn": "342-9876-54",
"sex" : "Male",
"country" : "USA",
"city" : "New York",
"phone" : "3346573924",
"military_branch" : "FBI",
"zip" : "25643",
"guid" : ""
},
{
"id": 2,
"first_name": "Neal",
"last_name": "caffery",
"middle_name": "Sam",
"DOB": "28/02/1988",
"ssn": "420-4204-20",
"sex" : "Male",
"country" : "USA",
"city" : "New York",
"phone" : "676554323",
"military_branch" : "Air Force",
"zip" : "26531",
"guid" : ""
},
]
here is my controller.js
var patientApp = angular.module('patientApp', []);
patientApp.controller('PatientListCtrl',['$scope','$http', function ($scope, $http) {
$http.jsonp('/json/patients.json').success(function (data) {
$scope.patients = data;
})
});
$scope.orderProp = 'id';
}]);
Here is my 'index.html' file
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" data-ng-app="patientApp">
<head>
<title>Patient Management</title>
<script src="js/angular.js"></script>
<script src="js/angular-resource.min.js"></script>
<script src="js/controller.js"></script>
</head>
<body data-ng-controller="PatientListCtrl">
<table>
<thead>
<tr>ID</tr>
<tr>First Name</tr>
<tr>Last Name</tr>
<tr>SSN</tr>
<tr>DOB</tr>
</thead>
</table>
<div data-ng-repeat="patient in patients">
<table>
<tr>{{patient.id}}</tr>
<tr>{{patient.last_name}}</tr>
<tr>{{patient.first_name}}</tr>
<tr>{{patient.SSN}}</tr>
<tr>{{patient.DOB}}</tr>
</table>
</div>
</body>
</html>
I think i'm missing something.
plz help me ,thanks in advance.
Why are you using jsonp. It will not work jsonp is a work around to get data from diferent domain sources what it does is creates a javascript tag in your page this javascript will load an execute a function that you already have define in your page. so returning the json will not execute the function. Will not work.
http://en.wikipedia.org/wiki/JSONP
It looks like you don't have a problem of different domain requests because the url that you are trying to access is /json/patiens.json so I can assume you are trying to load it from the same domain. If that is the case $http.get is the way to go.
One more thing your code needs to run from a web server. If you created this test page and you are trying to load it from the filesystem, my friend you are out of luck will never work. You can not make ajax calls to file:///
In the case you are running it from a web server check the mime type. It could be that the mime type in the response header is incorrect and the browser can not parse the document.
If you are using a decent browser (anything other that IE) you have very reliable good debugging tools check if your code is making a request to the server. And check what are you getting back including the headers specially the mime type. If you are using windows a great tool is fiddle.
Instead of $http.jsonp, use $http.get
$http.get('/json/patients.json').success(function (data) {
$scope.patients = data;
});
Check out this Plunkr
Say I submit a form via Ajax and need a response from the server:
Pass/fail indicator
On fail, a list of validation errors with associated field ids/names, etc
Is there a standard or best practice for the JSON format for such a structure? If so, I'd like to try to stick to it instead of coming up with my own convention.
OmniTI has a decent standard that I like and recommend: http://labs.omniti.com/labs/jsend
{
status : "success",
data : {
"posts" : [
{ "id" : 1, "title" : "A blog post", "body" : "Some useful content" },
{ "id" : 2, "title" : "Another blog post", "body" : "More content" },
]
}
}
I usually use a variant:
{
status : "error",
messages : {
"some_field" : "message"
}
}
Peter Bui's got this proposal format: http://paydrotalks.com/posts/45-standard-json-response-for-rails-and-jquery
{
status: "ok|redirect|error",
to: "http://www.redirect-url.com",
html: "<b>Insert html</b>",
message: "Insert some message here"
}
{
"result": "false",
"fields":
[
{"id": "element1", "name": "element1"},
{"id": "element2", "name": "element2"},
{"id": "element3", "name": "element3"}
]
}
Hmm. I don't know about a standard, but you might want to just do something like
{
"result": "false",
"errors":
[
{"errorCode": "1234", "errorText": "malformed address"},
{"errorCode": "5678", "errorText": "no username"}
]
}