Importing a JSON on angularJS with $http.get - json

Im learnign angularJs, and i want to import an array from a json on my controller Like that:
myApp.controller("demoCtrl", function ($scope, $http) {
var promise = $http.get("todo.json");
promise.then(function (data) {
$scope.todos = data;
});
});
and im using a table to display the data on todos:
<table class="table">
<tr>
<td>Action</td>
<td>Done</td>
</tr>
<tr ng-repeat="item in todos">
<td>{{item.action}}</td>
<td>{{item.done}}</td>
</tr>
</table>
and this results on the flowing html page:
<!DOCTYPE html>
<html ng-app="demo">
<head>
<title>Example</title>
<link href="../css/bootstrap.css" rel="stylesheet" />
<link href="../css/bootstrap-theme.css" rel="stylesheet" />
<script src="angular.js"></script>
<script type="text/javascript">
var myApp = angular.module("demo", []);
myApp.controller("demoCtrl", function ($scope, $http) {
var promise = $http.get("todo.json");
promise.then(function (data) {
$scope.todos = data;
});
});
</script>
</head>
<body ng-controller="demoCtrl">
<div class="panel">
<h1>To Do</h1>
<table class="table">
<tr>
<td>Action</td>
<td>Done</td>
</tr>
<tr ng-repeat="item in todos">
<td>{{item.action}}</td>
<td>{{item.done}}</td>
</tr>
</table>
</div>
</body>

The normal way of getting access to the json is from the data within the returned object from the http request - you are tying to use the entire returned object.
I use "response" as the return from the get request - then the data is "response.data". This is needed because there are other properties returned within the response object from the get request.
Try changing your promise to be as follows:
promise.then(function (response) {
$scope.todos = response.data;
});
Also you should be having a thead and th's and tbody in the table to show a more semantically correct table
<table class="table">
<thead>
<tr>
<th scope="col">Action</th>
<th scope="col">Done</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="item in todos">
<td>{{item.action}}</td>
<td>{{item.done}}</td>
</tr>
</tbody>
</table>

Promise return entire response in callback Data is in response.data
myApp.controller("demoCtrl", function ($scope, $http) {
var promise = $http.get("todo.json");
// Entire response in callback
promise.then(function (response) {
$scope.todos = response.data; // Data is in response.data
});
});
More: https://docs.angularjs.org/api/ng/service/$http

Related

Displaying multiple jsons in VUE

So this is my code
<script>
export default {
name: "app",
data() {
return {
items: []
};
},
created: function() {
this.makeAjaxCall("books.json", "get").then(res => {
this.items = res
return res
}),
this.makeAjaxCall("authors.json", "get").then(resA => {
this.items = resA
return resA
})
},
methods: {
makeAjaxCall:function(url, methodType){
var promiseObj = new Promise(function(resolve, reject){
var xhr = new XMLHttpRequest();
xhr.open(methodType, url, true);
xhr.send();
xhr.onreadystatechange = function(){
if (xhr.readyState === 4){
if (xhr.status === 200){
//alert("xhr done ok");
var response = xhr.responseText;
var respJson = JSON.parse(response);
resolve(respJson);
} else {
reject(xhr.status);
//alert("xhr failed");
}
} else {
//alert("xhr processing");
}
}
//alert("request sent succesfully");
});
return promiseObj;
}
}
};
</script>
<template>
<div id="app">
<table class="booksTable">
<thead>
<tr>
<th>Title</th>
<th>Author</th>
<th>Genre</th>
<th>Image</th>
<th>Availability</th>
<th>Options</th>
</tr>
</thead>
<tbody>
<tr v-for="item in items.books" :key="item.name">
<td>{{item.name}}</td>
<td>{{item.author}}</td>
<td>{{item.genre}}</td>
<td><img id="imageBook" :src="item.imageUrl"></td>
</tr>
</tbody>
</table>
</div>
</template>
I have the function makeAjaxCall that brings me the books.json, but I want to use it for multiple jsons.
I tried to call it under created, with a different json, authors.json, but it doesn't work.
I guess the syntax is wrong.
I know the function could have been created better, but I would like to keep its initial form or maybe add a parameter to be the json file.(Tried that, but didn't work for me)
Any ideas, pretty please?
To bind the data you have to declare first items: {books:[],authors:[]}
Also you are overwriting this.items use this.items.books and this.items.authors to assign.
Below is the example which works without ajax
new Vue ({
el: "#app",
data() {
return {
items: {books:[],authors:[]}
};
},
created: function() {
this.items.books = this.makeAjaxCall("books", "get");
this.items.authors = this.makeAjaxCall("authors", "get");
},
methods: {
makeAjaxCall:function(url, methodType){
if(url == 'books'){
promiseObj= [{name:'name11',author:'author11',genre:'genre11'},{name:'name12',author:'author12',genre:'genre12'}]
}else{
promiseObj= [{name:'name22',author:'author22',genre:'genre22'}]
}
return promiseObj;
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.21/vue.js"></script>
<div id="app">
<table class="booksTable">
<thead>
<tr>
<th>Title</th>
<th>Author</th>
<th>Genre</th>
<th>Image</th>
</tr>
</thead>
<tbody>
<tr v-for="item in items.books" :key="item.name">
<td>{{item.name}}</td>
<td>{{item.author}}</td>
<td>{{item.genre}}</td>
<td><img :src="item.imageUrl"></td>
</tr>
</tbody>
</table>
<table class="authorsTable">
<thead>
<tr>
<th>Title</th>
<th>Author</th>
<th>Genre</th>
<th>Image</th>
</tr>
</thead>
<tbody>
<tr v-for="item in items.authors" :key="item.name">
<td>{{item.name}}</td>
<td>{{item.author}}</td>
<td>{{item.genre}}</td>
<td><img :src="item.imageUrl"></td>
</tr>
</tbody>
</table>
</div>
So I found the answer, after millions of tries and it's pretty simple.
<script>
import './styling.scss'
export default {
name: "app",
data() {
return {
items: {books:[], authors:[]}
};
},
created: function() {
this.makeAjaxCall("books.json", "get").then(res => {
this.items.books = res.books;
return res;
}),
this.makeAjaxCall("authors.json", "get").then(res => {
this.items.authors = res.authors;
return res;
})
},
methods: {
makeAjaxCall:function(url, methodType){
var promiseObj = new Promise(function(resolve, reject){
var xhr = new XMLHttpRequest();
xhr.open(methodType, url, true);
xhr.send();
xhr.onreadystatechange = function(){
if (xhr.readyState === 4){
if (xhr.status === 200){
//alert("xhr done ok");
var response = xhr.responseText;
var respJson = JSON.parse(response);
resolve(respJson);
} else {
reject(xhr.status);
//alert("xhr failed");
}
} else {
//alert("xhr processing");
}
}
//alert("request sent succesfully");
});
return promiseObj;
}
}
};
</script>
<template>
<div id="app">
<table class="booksTable">
<thead>
<tr>
<th>Title</th>
<th>Author</th>
<th>Genre</th>
<th>Image</th>
<th>Availability</th>
<th>Options</th>
</tr>
</thead>
<tbody>
<tr v-for="item in items.books" :key="item.name">
<td>{{item.name}}</td>
<td>{{item.author}}</td>
<td>{{item.genre}}</td>
<td><img id="imageBook" :src="item.imageUrl"></td>
<td>
<button class="btn add"> Add</button>
<button class="btn edit"> Edit</button>
<button class="btn delete"> Delete</button>
</td>
</tr>
</tbody>
</table>
</div>
</template>

Add a table row from JSON input

I am trying to add a row to a HTML table from JSON input using AJAX. I only want specific columns added. I am able to get the table to show; however the rows are not added.
Please see below for the HTML and AJAX (with the returned JSON).
HTML:
<html>
<head>
<link rel="stylesheet" href="https://cdn.datatables.net/1.10.7/css/jquery.dataTables.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="https://cdn.datatables.net/1.10.7/js/jquery.dataTables.min.js"></script>
<script src="js/table2excel.js"></script>
<link rel="stylesheet" href="style.css">
<script src="js/tableTest.js"></script>
</head>
<body>
<p><button id="btn-export">Export</button></p>
<table id="example" class="display" cellspacing="0" width="100%">
<thead>
<tr>
<th>Activity Name</th>
<th>Start Date</th>
<th>End Date</th>
</tr>
</thead>
<tbody>
<tr>
<td id='adActivityName'></td>
<td id='adStartDate'></td>
<td id='adEndDate'></td>
</tr>
</tbody>
</table>
</body>
</html>
AJAX (with JSON):
function e1ActivitySelect() {
var dataToBeSent = {
ssAccountLevel : sessionStorage.getItem('ssAccountLevel'),
ssAccountID : sessionStorage.getItem('ssAccountID'),
ssArchived : sessionStorage.getItem('ssArchived'),
};
$.ajax({
url: "E1ActivitySelectView",
data : dataToBeSent,
type: "POST",
cache: false
})
.fail (function(jqXHR, textStatus, errorThrown) {
$('#ajaxGetUserServletResponse').text('An error occured getting the Activity information.');
})
.done(function(responseJson1a) {
dataType: "json";
// alert(JSON.stringify(responseJson1a));
// [{"adId":"2","grpId":"2","adActivityID":"2","adActivityName":"Visit Ryde Fire Station","adStartDate":"2017-05-24","adEndDate":"2017-05-24"}]
for (i=0; i < responseJson1a.length; i++) {
$('#adActivityName').append("<td>"+a[i].adActivityName+"</td>");
$('#adStartDate').append("<td>"+a[i].adStartDate+"</td>");
$('#adEndDate').append("<td>"+a[i].adEndDate+"</td>");
}
});
}
You are Not appending table rows in a proper way
When you have multiple rows to append you need to create multiple row tags and append the data like this
HTML:
<table id="example" class="display" cellspacing="0" width="100%">
<thead>
<tr>
<th>Activity Name</th>
<th>Start Date</th>
<th>End Date</th>
</tr>
</thead>
<tbody id="mytablebody">
</tbody>
</table>
Javascript:
function e1ActivitySelect() {
var dataToBeSent = {
ssAccountLevel : sessionStorage.getItem('ssAccountLevel'),
ssAccountID : sessionStorage.getItem('ssAccountID'),
ssArchived : sessionStorage.getItem('ssArchived'),
};
$.ajax({
url: "E1ActivitySelectView",
data : dataToBeSent,
type: "POST",
cache: false
})
.fail (function(jqXHR, textStatus, errorThrown) {
$('#ajaxGetUserServletResponse').text('An error occured getting the Activity
information.');
})
.done(function(responseJson1a) {
var tablebody = "";
try{
for (i=0; i < responseJson1a.length; i++) {
tablebody += "<tr><td>"+responseJson1a[i].adActivityName+"</td><td>"++responseJson1a[i].adStartDate+"</td><td>"++responseJson1a[i].adEndDate+"</td></tr>";
}
$("#mytablebody").empty();
$("#mytablebody").append(tablebody);
}
catch(e){
console.log(e);
}
});
}

Parse a remote JSON file using header in Angular 5

I need to parse a remote JSON file using a header with a get request in Angular 5. Not sure how to do it with GET along with header.
Something like this but in Angular 5:
let headers = new Headers({
'key': 'Value',
'key2' :'value2'
});
let request_option = new RequestOptions({ headers: this.headers});
this.http.get("http.//.....", request_option)
.map(res => res.json()
this.user.firstname = user.response.docs[0].FIRST_NAME;
this.user.lastname = user.response.docs[0].LAST_NAME;
JSON:
{
"responseHeader": {
"status":0,
"QTime":1,
},"response":{
"docs":[{
"FIRST_NAME": "John",
"LAST_NAME": "Smith"
}]
}
}
& finally be able to call it in HTML:
<div>{{user.firstname}}</div>
Below is the example for getting json from another server
$scope.userData = undefined;
var req = {
method: 'GET',
url: 'https://randomuser.me/api/?results=30&nat=US',
headers: { 'Content-Type': 'application/json' }
};
$http(req).then(function (response) {
$scope.userData = response.data;
});
If the response.data is recieved in json string, you can easily parse it using following code
JSON.stringify(response.data)
Below is the working example for getting json from another server and display it in table
<!DOCTYPE html>
<html>
<head>
<script data-require="jquery#3.0.0" data-semver="3.0.0" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0/jquery.js"></script>
<link data-require="bootstrap#3.3.7" data-semver="3.3.7" rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" />
<script data-require="angular.js#1.6.6" data-semver="1.6.6" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.6/angular.min.js"></script>
<script src="https://angular-ui.github.io/bootstrap/ui-bootstrap-tpls-0.6.0.js" type="text/javascript"></script>
<script>
(function() {
angular.module("testApp", ['ui.bootstrap']).controller('testCtrl', ['$scope', '$http', function($scope, $http) {
$scope.userData = undefined;
var req = {
method: 'GET',
url: 'https://randomuser.me/api/?results=30&nat=US',
headers: { 'Content-Type': 'application/json' }
};
$http(req).then(function (response) {
$scope.userData = response.data;
});
}]);
}());
</script>
<style></style>
</head>
<body ng-app="testApp">
<div ng-controller="testCtrl">
<form name="commonForm">
<table class="table">
<tr>
<th> Name </th>
<th> Gender </th>
<th> Email </th>
<th> Username </th>
<th> Date of Birth </th>
<th> Registered Date </th>
<th> Phone </th>
<th> Mobile </th>
<th> Nationality </th>
<th> Profile </th>
</tr>
<tr ng-repeat="user in userData.results">
<td> {{user.name.first}} {{user.name.last}}</td>
<td> {{user.gender}}</td>
<td> {{user.email}}</td>
<td> {{user.login.username}}</td>
<td> {{user.dob}}</td>
<td> {{user.registered}}</td>
<td> {{user.phone}}</td>
<td> {{user.cell}}</td>
<td> {{user.nat}}</td>
<td>
<img ng-src="user.picture.large">
</td>
</tr>
</table>
</form>
</div>
</body>
</html>
In Angular 5 you can use property binding to access properties of DOM elements, in test case:
<div [innerHTML]="post.body"></div>
for reference look here angular.io docs

unable to Retrieve data from JSON file using Angular js

enter image description hereI am not able Retrieve data from Json file using Angular Js.
Am trying to get the Json data from URL using click function in angular Js and also when click the button add empty tr td in table.
<!doctype html>
<html lang="en" ng-app="sampleapp">
<head>
{% load staticfiles %}
<meta charset="utf-8">
<link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.min.css">
<script src="{% static 'bootstrap/js/angular.min.js'%}"></script>
<script type="text/javascript" src="{% static 'bootstrap/js/jquery.min.js'%}"></script>
<script src="{% static 'bootstrap/js/bootstrap.min.js'%}" type="text/javascript"></script>
<script type="text/javascript" src="{% static '/bootstrap/js/app_ang.js'%}"></script>
</head>
<body >
<div class="col-sm-12" ng-controller="tablejsonCtrl">
<button class="clickbutton" ng-click="jsonclick();">Show-json</button>
<table rule="all" class="table table-bordered table-hover ">
<tr>
<th>Name</th>
<th>Price</th>
<th>Description</th>
<th>Calories</th>
<th>isbest</th>
</tr>
<tr ng-repeat="value in students.breakfast_menu.food">
<td>{{value.name}}</td>
<td>{{value.price}}</td>
<td>{{value.description}}</td>
<td>{{value.calories}}</td>
<td>{{value.isbest}}</td>
</tr>
</table>
</div>
</body>
</html>
var app =angular.module('sampleapp', [])
app.controller("tablejsonCtrl", function ($scope, $http) {
$scope.jsonclick = function () {
var url = "http://127.0.0.1:8000/static/waste/test.json";
$http.get(url).then(function(response) {
$scope.students = response.data;
});
}
});
Instead of use ".then" try with .success method, so replace this :
$http.get(url).then(function(response) {
$scope.students = response.data;
});
with this :
$http.get('url').success(function (response){
$scope.students= response;
});
You can use HTTP request in local.
Only works for Angular Versions above 1.6
$http.get('./path-to-JSON-file/../someFile.json').
then(function onSuccess(response) {
angular.extend(_this, data);
defer.resolve();
}).
catch(function onError(response) {
console.log(response);
});
for further research: CLICK HERE

using ng-repeat to display data in json file

I am new to angularjs. I want to display the data in the following json file using ng-repeat.
http://www.cricbuzz.com/api/match/current
But I'm confused as there is a number in the data as key to each object. Can someone help me?
THis is a basic way to do it
Partial
<div ng-controller="Ctrl" >
<table>
<thead>
<tr>
<th>Id</th>
<th>Name</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="row in rows">
<td>#{{ row.id}}</td>
<td>{{ row.series.name | uppercase }}</td>
</tr>
</tbody>
</table>
</div>
Controller
angular.module('app').controller('Ctrl', ['$scope', 'Resource', function ($scope, Resource) {
var pageChanged = function () {
$scope.myPromise = Resource.get({}, function (response) {
$scope.rows = response;
});
};
pageChanged();
}])
.factory('Resource', ['$resource', function($resource) {
return $resource('http://www.cricbuzz.com/api/match/current', {
}, {
'get': {
method: 'GET',
headers: {"Content-Type": "application/json"}
}
});
}]);