How to print json data on view page coming from Server - javascript

I am very new to jquery. I have an api '/categories' which returns me json object of categories. Response is like in this format:
[
{
name: "Laptop deals",
slug: "laptop-deals",
imageURL: "image.jpg",
id: 1
},
{
name: "Fashion deals",
slug: "fashion-deals",
imageURL: "image.jpg",
id: 2
},
{
name: "Mobile deals",
slug: "mobile-deals",
imageURL: "image.jpg",
id: 3
},
{
name: "Home & Kitchen deals",
slug: "home-and-kitchen-deals",
imageURL: "image.jpg",
id: 4
},
]
I want to access this in my html view to display.I have tried this:
<script>
$(document).ready(function(){
$("button").click(function(){
$.getJSON('/categories',function(data){
$.each(function(obj,ind,data){
$('#div').append(obj.slug);
});
});
});
});
</script>
</head>
<body>
<button>Get JSON data</button>
<div></div>
</body>
But it doesnt do anything when i click on button. I have tried previous post on stack overflow but nothing works

Change
$.each(function(obj,ind,data){
$('#div').append(obj.slug);
});
into
$.each(data, function(i, item) {
$('div').append(data[i].slug);
//or
//$('div').append(item.slug);
});​

Related

Retreiving specific data from JSON repsonse only in certain array indexes

Hey sorry if this has been asked before, I haven't found an answer that has helped me.
I am working on building a personal application using the free Ticketmaster application but I'm having trouble with the JSON response.
An example of the response is:
data: {
classifications: [
type: {
id: 1,
name: "Dont want this"
}
],
[
type: {
id: 2,
name: "Dont want this"
}
],
[
category: {
id: 3,
name: "Food & Drink"
}
],
[
category: {
id: 4,
name: "Music"
]
}
I am trying to retrieve category names such as "Family", "Food & Drink", "Music" etc but only at some indexes does the array have category objects, the others have type.
Can someone tell me how to go through this array and only get the name when it is at category.name?
Any help is appreciated :)

How to render JSON Array using handlebars

I am trying to render a repeating UI component with Handlebars.js..
<div class="container-fluid article-container">
{{#each this}}
<h1>{{header}}</h1>
<h1>{{url}}</h1>
<h1>{{body}}</h1>
{{/each}}
</div>
The JSON Data coming back from the API Server is given below..
router.get("/api/fetch", function(req, res) {
var respData = [
{
header: "U.S. Releases Surveillance Records of Ex-Trump Aide",
url:
"https://www.nytimes.com/2018/07/21/us/politics/carter-page-fisa.html",
body:
"The release offered a rare glimpse of national security wiretap files and raised echoes of a fight in February over the Russia inquiry between Republicans and Democrats on the House Intelligence Committee."
}
];
res.render("index", respData);
});
The H1 tags are showing up empty in the UI when the browser renders the page.. Can someone please help me out?
For example, if you api data is coming back as this:
var icecreams = [
{ name: "vanilla", price: 10, awesomeness: 3 },
{ name: "chocolate", price: 4, awesomeness: 8 },
{ name: "banana", price: 1, awesomeness: 1 },
{ name: "greentea", price: 5, awesomeness: 7 },
{ name: "jawbreakers", price: 6, awesomeness: 2 },
{ name: "vanilla", price: 10, awesomeness: 3 }
];
Then your handlebar file would be
{{#each ics}}
<p>Flavor: {{name}}</p>
<p>Price: ${{price}}</p>
<p>Awesomeness: {{awesomeness}}</p>
<hr>
{{/each}}
Express route:
app.get("/icecreams", function(req, res) {
res.render("ics", { ics: icecreams });
});
This will render all the ice-creams. For your example, it will just render one.
This example is taken from one of my demos.

AngularJS: get object property in array by matching a different property?

I have an array of products, displayed in a table with an AngularJS ng-repeat.
The products are an array of objects returned from a Wordpress REST API call, and each object has a "category", which returns as a number.
Example: { "name": "Foo", "cat": 12 }
I can't simply bind to the "cat" property, since it displays "12" and I want to display the category label instead.
I can query for the list of all categories, and get an array like so:
[
{ label: 'Customer Engagement Solutions', id: 2 },
{ label: 'Small and Medium Business', id: 13 },
{ label: 'Customer Information Management', id: 4 },
{ label: 'eCommerce', id: 25 },
{ label: 'Location Intelligence', id: 16 },
{ label: 'Enterprise', id: 12 }
]
My product above, "Foo" should display "Enterprise", which is 12.
I know I can bind to a function, as in {{ctrl.getCat(product)}} but I'm not sure how to do the matching of the ID in the product to the one in the category array, and return the category label.
This is trivial to do in actual Wordpress PHP as they provide a function for this very task.
Use Array#find() or even more performant is create a hashmap of the category labels using id as property keys
Using find()
ctrl.getCat = function(product){
let cat = categories.find(e => e.id === product.cat)
return cat ? cat.label : 'Unknown';
}
Or as hashmap:
ctrl.catLabels = categories.reduce((a,c) => { a[c.id] = c.label; return a;},{})
Then in view:
{{ctrl.catLabels[product.cat]}}
The easiest way would be to create a new array of products that already maps the categories. When you initialize the controller with the products and categories, create a new array the maps it.
var app = angular.module('app', []);
app.controller('MainCtrl', function($scope) {
const _categories = [
{ label: 'Customer Engagement Solutions', id: 2 },
{ label: 'Small and Medium Business', id: 13 },
{ label: 'Customer Information Management', id: 4 },
{ label: 'eCommerce', id: 25 },
{ label: 'Location Intelligence', id: 16 },
{ label: 'Enterprise', id: 12 }
];
const _products = [
{ "name": "Foo", "cat": 12 },
{ "name": "Bar", "cat": 16 },
{ "name": "Foo Bar", "cat": 12}
]
let categoryMap = {}
_categories.forEach( (category)=>{
categoryMap[category.id] = category.label;
})
this.products = _products.map( (product)=>{
return {
"name": product.name,
"category": categoryMap[product.cat]
}
})
});
<!DOCTYPE html>
<html ng-app="app">
<head>
<script data-require="angular.js#1.5.x" src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.11/angular.min.js" data-semver="1.5.11"></script>
</head>
<body ng-controller="MainCtrl as ctrl">
<div ng-repeat="product in ctrl.products">
<span>Name: {{product.name}}</span> <span>Category: {{product.category}}</span>
</div>
</body>
</html>

How to parse a Non-Json data hemera

I am new to Json and JavaScript. Currently I have a url which returns a JSON response. But the problem is that, It is not in correct format. Please see my response below
var pd={ player:
{ id: 363609002,
game: 'bf4',
plat: 'pc',
name: 'm4jes',
tag: 'BPt',
dateCheck: 1487204427149,
dateUpdate: 1474581052618,
dateCreate: 1384980182606,
dateStreak: 1474581052618,
lastDay: '20160715',
country: '',
countryName: null,
rank:
{ nr: 121,
imgLarge: 'bf4/ranks/r121.png',
img: 'r121',
name: 'Major General II',
needed: 16110000,
next:
{ nr: 122,
imgLarge: 'bf4/ranks/r122.png',
img: 'r122',
name: 'Major General III',
needed: 16750000,
curr: 16720600,
relNeeded: 640000,
relCurr: 610600,
relProg: 95.40625 } },
score: 16724643,
timePlayed: 1476950,
uId: '2832665149467333131',
uName: 'm4jes',
uGava: '721951facb53ed5632e196932fb6c72e',
udCreate: 1319759388000,
privacy: 'friends',
blPlayer: 'http://battlelog.battlefield.com/bf4/soldier/m4jes/stats/363609002/pc/',
blUser: 'http://battlelog.battlefield.com/bf4/user/m4jes/',
editable: false,
viewable: true,
adminable: false,
linked: false },}
from the above response I have to get the output as :
{
game: 'bf4',
plat: 'pc',
name: 'm4jes',
tag: 'BPt',
score: 16724643,
timePlayed: 1476950
}
By which method I can get the required out in Javascript
First of all the URL is not returning a JSON response but a JS object literal. The difference is explained here.
You have to get the string from the url. You can use the jQuery method get():
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
var jqxhr = $.get( "https://api.bf4stats.com/api/playerInfo?plat=pc&name=m4jes&output=js", function() {
//Insert the rest of the code here
});
</script>
Then, jqxhr.responseText is the string which correspond to the object we want. With eval, we transform the string into an object:
pd = eval(jqxhr.responseText);
So here we have an object literal with all the pairs name/value. You can access the values you want by using the dot notation. If you want to get the name of the game for example, you can write this:
pd.player.game
So this leads to :
var myNewObject = {
game: pd.player.game,
plat: pd.player.plat,
name: pd.player.name,
tag: pd.player.tag,
score: pd.player.score,
timePlayed: pd.player.timePlayed,
}
Then, you have to transform this JS object literal into a JSON by using the JSON.stringify() method:
console.log(JSON.stringify(myNewObject, null, '\t'));
It returns what you want:
{
"game": "bf4",
"plat": "pc",
"name": "m4jes",
"tag": "BPt",
"score": 16724643,
"timePlayed": 1476950
}
So here is the full code:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
var jqxhr = $.get( "https://api.bf4stats.com/api/playerInfo?plat=pc&name=m4jes&output=js", function() {
pd = eval(jqxhr.responseText);
var myNewObject = {
game: pd.player.game,
plat: pd.player.plat,
name: pd.player.name,
tag: pd.player.tag,
score: pd.player.score,
timePlayed: pd.player.timePlayed,
}
console.log(JSON.stringify(myNewObject, null, '\t'));
});
</script>

angularjs - cascading selects use model data from first select

I'm attempting to get at the version data stored inside the server model, however, it's not playing ball.
My assumption is that on load the initial data from the first select is not yet available because it hasn't really been selected (technically speaking). I tried to use trigger('click') whether this would help at all, but it did absolutely nothing. I can't seem to find any answers out there and I have a feeling I maybe tackling it from the wrong end.
edit: Forgot to mention, if I have to restructure my data to allow for this to happen, so be it.
Here's all my code + JSFiddle:
http://jsfiddle.net/h8uoy9xr/3/
HTML:
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.1/angular.min.js"></script>
<div ng-app>
<div ng-controller="MyCntrl">
<div class="selection" ng-repeat="selection in selections">
<select ng-model="server" ng-options="server as server.name for server in servers track by server.id" ng-init="server.id=selection.server"></select>
{{ server | json }}
<select ng-model="version" ng-options="version as version.name for version in server.version track by version.id" ng-init="version.id=selection.version"></select>
</div>
</div>
</div>
JS:
function MyCntrl($scope) {
$scope.servers = [
{
"id": 1,
"name": "server1",
"version":
[
{
id:1,
name: "10.x"
},
{
id:3,name: "12.x"
}
]
},
{
"id": 2,
"name": "server2",
"version":
[
{
id: 2,
name: "1.0"
},
{
id: 3,
name: "2.0"
}
]
}
];
$scope.selections = [
{
server: 2,
version: 3
},
{
server: 1,
version: 3
}
];
}
cascading dropdownlist inside ng-repeat
Here's a working solution of the above problem. I hadn't realized angularjs did things a wee bit differently with the models, but finally it clicked. See below code + fiddle for anyone needing something similar in the future:
Fiddle: http://jsfiddle.net/mmy6z57g/2/
Fiddle: http://jsfiddle.net/mmy6z57g/3/ (added a button to demonstrate how additional servers can be added)
HTML:
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular.min.js"></script>
<div ng-app="test">
<div ng-controller="MyCntrl">
<div class="selection" ng-repeat="xserver in xservers">
<select ng-model="xservers[$index]" ng-options="server as server.name for server in servers track by server.id"></select>
<select ng-model="xversions[$index]" ng-options="version as version.name for version in xservers[$index].version track by version.id"></select>
</div>
</div>
</div>
JS:
var app = angular.module('test', []);
app.controller('MyCntrl', function($scope) {
$scope.servers = [
{
id: 1,
name: "server1",
version:
[
{
id:1,
name: "10.x"
},
{
id:3,
name: "12.x"
}
]
},
{
id: 2,
name: "server2",
version:
[
{
id: 2,
name: "1.0"
},
{
id: 3,
name: "2.0"
}
]
}
];
$scope.xservers = [
{
id: 2,
name: "server2",
version:
[
{
id: 2,
name: "1.0"
},
{
id: 3,
name: "2.0"
}
]
},
{
id: 1,
name: "server1",
version:
[
{
id:1,
name: "10.x"
},
{
id:3,
name: "12.x"
}
]
}
];
$scope.xversions = [
{
id: 3,
name: "2.0"
},
{
id: 3,
name: "12.x"
}
];
});
Could you use your controller and use a .then(); so that it selects the first one and when that is done then it selects the second? User wouldn't see it and it would solve the issue of second one not getting selected.

Categories