unable to fetch data from json file in angularjs? - javascript

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

Related

Angular 1.6 $http.get unable to read from json

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;

Angularjs orderby on toggle and removing orderby

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!

How to populate table values dynamically based on JSON in datatable angular?

I'm using Angular-Datatables. I need to be able to dynamically create the table based on the data that is being returned. In other words, I do not want to specify the column headers.
Example:
json data:
[
{
"id": "2",
"city": "Baltimore",
"state": "MD",
},
{
"id": "5",
"city": "Boston",
"state": "MA",
},
{
"id": "8",
"city": "Malvern",
"state": "PA",
},
]
Column Headers:
id, city, state
Can someone please help with this?
That is actually a good question! With traditional jQuery dataTables it is not a problem, but we have a different kind of declarative setup with angular dataTables, making it more difficult to separate the various tasks. We can delay the population of data with fromFnPromise, but not prevent the dataTable from being instantiated before we want it. I think I have found a solid solution :
First, to avoid instant initialization remove the datatable directive from the markup and give the <table> an id instead, i.e :
<table id="example" dt-options="dtOptions" dt-columns="dtColumns" />
Then load the data resource, build dtColumns and dtOptions and finally inject the datatable attribute and $compile the <table> using the id :
$http({
url: 'data.json'
}).success(function(data) {
var sample = data[0], dtColumns = []
//create columns based on first row in dataset
for (var key in sample) dtColumns.push(
DTColumnBuilder.newColumn(key).withTitle(key)
)
$scope.dtColumns = dtColumns
//create options
$scope.dtOptions = DTOptionsBuilder.newOptions()
.withOption('data', data)
.withOption('dataSrc', '')
//initialize the dataTable
angular.element('#example').attr('datatable', '')
$compile(angular.element('#example'))($scope)
})
This should work with any "array of objects" resource
Demo -> http://plnkr.co/edit/TzBaaZ2Msd9WchfLDLkN?p=preview
NB: Have cleaned up the example JSON, I guess it was a sample and not meant to be working with trailing commas.
Being faced with the same problem, I actually found an easier to implement and much simpler (and safer because of not using $compile) solution.
The only change needed to be made to the html is the addition of an ng-if:
<table ng-if="columnsReady" datatable="" dt-options="dtOptions" dt-columns="dtColumns"/>
What happens is that angular will delay the creation of this node till columnsReady has any value. So now in your code you can get the data you need, and when you have it, you can just set columnsReady to true and angular will do the rest.
$http({
url: 'data.json'
}).success(function(data) {
var sample = data[0], dtColumns = []
//create columns based on first row in dataset
for (var key in sample) dtColumns.push(
DTColumnBuilder.newColumn(key).withTitle(key)
)
$scope.dtColumns = dtColumns
//create options
$scope.dtOptions = DTOptionsBuilder.newOptions()
.withOption('data', data)
.withOption('dataSrc', '')
//initialize the dataTable
$scope.columnsReady = true;
});
Below code which will give you table dynamically based on data
HTML
<div ng-controller="WithAjaxCtrl as showCase">
<table datatable="" dt-options="showCase.dtOptions" dt-columns="showCase.dtColumns" class="row-border hover"></table>
JS
angular.module('showcase.withAjax',['datatables']).controller('WithAjaxCtrl', WithAjaxCtrl);
function WithAjaxCtrl(DTOptionsBuilder, DTColumnBuilder) {
var vm = this;
vm.dtOptions = DTOptionsBuilder.fromSource('data.json')
.withPaginationType('full_numbers');
vm.dtColumns = [
DTColumnBuilder.newColumn('id').withTitle('ID'),
DTColumnBuilder.newColumn('city').withTitle('City'),
DTColumnBuilder.newColumn('state').withTitle('State')
];
}
data.json
[{
"id": 860,
"city": "Superman",
"state": "Yoda"
}, {
"id": 870,
"city": "Foo",
"state": "Whateveryournameis"
}, {
"id": 590,
"city": "Toto",
"state": "Titi"
}, {
"id": 803,
"city": "Luke",
"state": "Kyle"
},
...
]

How to render mustache using : external json that have function as variable

I want to render mustache.js example. but I want to get data from external file.
I copy this data to "mydata.json" :
{
"beatles": [
{ "firstName": "John", "lastName": "Lennon" },
{ "firstName": "Paul", "lastName": "McCartney" },
{ "firstName": "George", "lastName": "Harrison" },
{ "firstName": "Ringo", "lastName": "Starr" }
],
"name": function () {
return this.firstName + " " + this.lastName;
}
}
I copy template to "template.html" :
{{#beatles}}
* {{name}}
{{/beatles}}
and render this files by this code :
$.get('template.html', function(template)
{
$.get('mydata.json',function(datas)
{
var rendered = Mustache.render(template, datas);
$('#content').html(rendered);
}
}
these codes not working until I remove function(s) from data file.
I tried : different 'dataType' in JQuery ajax request.
I tried : get data as text and then jQuery.parseJSON that data.
I tried : regular and LAMBDA syntax in functions scripts.
but I cant solve this problem.
I find the answer .
AJAX request datatype must be 'script' to receive data as json and function together.

Using AngularJS to consume REST

I've made a REST api using Flask which gives a JSON response on http://localhost:5000/api/person giving the id,names and phone numbers of all the people in a SQLite database. http://localhost:5000/api/person/Name_of_person gives the JSON response corresponding to a person's name. I want to use AngularJS to consume the API so that I can output the names of all the people along with their phone numbers.
index.html
<!DOCTYPE html>
<html>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<body>
<div ng-app="myApp" ng-controller="customersCtrl">
<ul>
<li ng-repeat="x in myData">
{{ x.id }} + ', ' + {{x.name }} + ',' + {{x.phone}}
</li>
</ul>
</div>
<script>
var app = angular.module('myApp', []);
app.controller('customersCtrl', function($scope, $http) {
$http.get("http://localhost:5000/api/person").then(function (response) {
$scope.myData = response.data.objects;
});
});
</script>
</body>
</html>
Contents of http://localhost:5000/api/person
{
"num_results": 5,
"objects": [
{
"id": 24,
"name": "Name2",
"phone": "9999192938"
},
{
"id": 23,
"name": "Name3",
"phone": "9999192938"
},
{
"id": null,
"name": "Name4",
"phone": "9999192938"
},
{
"id": 21,
"name": "Name5",
"phone": "9999192938"
},
{
"id": null,
"name": "Name6",
"phone": "9999192938"
}
],
"page": 1,
"total_pages": 1
}
I am pretty sure my syntax is correct but I am getting no output for index.html. Can anyone please explain where I am going wrong? Is it maybe because it is on a local server and is unable to retrieve the data?
Please test the api by REST client, if the API returns proper result.
If you are having problem in running the application, please test using firefox browser. For chrome you need to serve the index.html through any server as it blocks file:/// protocol and needs http:// to run properly.
Make sure your API supports CORS. You have to set it in API end (see Flask docs) or else you can use CORS plugin for chrome.
If still problem persists there might be any logical/syntactical error. Please paste/share screenshot of your browser console.

Categories

Resources