Parse a remote JSON file using header in Angular 5 - html

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

Related

Passing JSON to Controller and save changes into database

Currently I am working on an ASP.NET Core MVC project. I want to implement in-line editing. Therefore tha plan is to pass the data in a JSON format to the controller and save it. Problem is, I am unable to do so.
My Controller: DenoProfileController
[HttpPost]
public ActionResult Update(DenoProfile denoprofile)
{
DenoProfile emp = db.DenoProfile.Single(em => em.DenoProfileID == denoprofile.DenoProfileID);
emp.NetworkNumber = denoprofile.NetworkNumber;
db.Entry(emp).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("IndexDenoProfile", new { id = 0 });
}
My View:
#model IEnumerable<CRUD_Profile_Creation.Models.ProfileCreationContext>
#{
ViewData["Title"] = "DenoProfile";
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript">
$(function () {
$('.edit-mode').hide();
$('.edit-user, .cancel-user').on('click', function () {
var tr = $(this).parents('tr:first');
tr.find('.edit-mode, .display-mode').toggle();
});
$('.save-user').on('click', function () {
var tr = $(this).parents('tr:first');
var NetworkNumber = tr.find("#NetworkNumber").html();
//Creating Employee JSON object
var EmployeeModel =
{
"NetworkNumber": NetworkNumber,
};
console.log(EmployeeModel.value);
//Posting Employee object to controller's Update action method
$.ajax({
url: "DenoProfile/Update",
data: JSON.stringify(EmployeeModel),
type: 'POST',
contentType: 'application/json; charset=utf-8',
dataType: "json",
success: function (data) {
tr.find('.edit-mode, .display-mode').toggle();
alert('Record updated Successfully!!');
}
});
});
$('.edit-user').on('click', function () {
var tr = $(this).parents('tr:first');
var NetworkNumber = tr.find("#NetworkNumber").html();
tr.find("#lblNetworkNumber").text(NetworkNumber);
});
})
</script>
<div class="container-fluid" align="center" justify-content="center" style="background-color:white;">
<h1>List of Clients</h1>
<a class="btn btn-success" asp-area="" asp-controller="DenoProfile" asp-action="AddDenoProfile">Profile Creation</a>
<br />
<br />
<table class="table-striped table-bordered">
<thead>
<tr align="center" justify-content="center">
<th>
Deno Profile ID
</th>
<th>
Network Number
</th>
</tr>
</thead>
<tbody>
#foreach (var item in (IEnumerable<CRUD_Profile_Creation.Models.DenoProfile>)ViewBag.DenoProfile)
{
<tr align="center" justify-content="center">
<td>
#Html.DisplayFor(modelItem => item.DenoProfileID)
</td>
<td>
<div class="display-mode" id="lblNetworkNumber">
#Html.DisplayFor(modelItem => item.NetworkNumber)
</div>
<div class="edit-mode">
<input type="text" id="NetworkNumber" value="#item.NetworkNumber" class="edit-mode" />
</div>
</td>
<td>
<button class="edit-user display-mode">Edit</button>
<button class="save-user edit-mode">Save</button>
<button class="cancel-user edit-mode">Cancel</button>
<button class="btn btn-danger"> #Html.ActionLink("Delete Deno Profile", "DeleteDenoProfile", new { id = item.DenoProfileID })</button>
</td>
</tr>
}
</tbody>
</table>
<br />
<br />
<br />
<br />
</div>
Thank you to anyone who can answer or comment my post!
I think I might pass the wrong value into the function. But i am not so sure. This is also my first time trying to pass JSON or anything ajax. If you guys want to leave some tips for me down below, it is very much appreciated.

Importing a JSON on angularJS with $http.get

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

how to print the JSON-RPC output which is in JSON format in a html-table format

Basically, I have a setup which has a client and a server.
The client side is implemented in angularjs which sends the get request to the server, which is in python, that connects to mongoDB and retrieves the result and sends back the response in the json format.
the request which I had sent is the following:
const data = {
"jsonrpc" : "2.0",
"method" : "faultall",
"id" : "1",
"params": {'argument' : 'something' }
}
this.http.post('http://localhost:80/jsonrpc',data).subscribe( res => console.log(this.json =res.text()))
While the response I got is:
{"result": [["water", "001"], ["water", "002"], ["temp", "003"]], "id": "1", "jsonrpc": "2.0"}
Now I want the response to be printed as a table in my html page like shown in the image:
Maybe, this code will useful
class AppController {
constructor($q) {
this.deferred = $q.defer();
}
getData() {
const response = {"result": [["water", "001"], ["water", "002"], ["temp", "003"]], "id": "1", "jsonrpc": "2.0"};
setTimeout(() => {
this.deferred.resolve(response.result);
}, 1000);
return this.deferred.promise;
}
fillTable() {
this.dataLoading = true;
this.getData()
.then(data => {
this.data = data;
this.dataLoading = false;
});
}
}
angular.module('app', [])
.controller('appController', AppController);
AppController.$inject = ['$q'];
angular.bootstrap(
document.getElementById('root'),
['app']
);
html, body {
height: 100%;
width: 100%;
display: flex;
align-items: center;
justify-content: center;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.5/angular.min.js"></script>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">
<div id="root" ng-controller="appController as ctrl">
<div style="margin: 1rem;">
<button
class="btn btn-primary"
ng-click="ctrl.fillTable()"
>
<span ng-bind="ctrl.dataLoading ? 'Loading' : 'Fetch data'"></span>
</button>
</div>
<table class="table" ng-show="ctrl.data.length > 0">
<thead>
<tr>
<th>Name</th>
<th>Id</th>
</tr>
</thead>
<tr ng-repeat="row in ctrl.data">
<td ng-bind="::row[0]"></td>
<td ng-bind="::row[1]"></td>
</tr>
<tbody>
</tbody>
</table>
<pre>{{ $ctrl.data | json}}</pre>
</div>

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

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"}
}
});
}]);