I'm just starting to use javascript and json.
I need to read data (get Information function) from a json file when processing an event in a javascript function without using jquery or any other librery. I don't know if I am missing something in the code, or if I have to create an Request and handle the callback, or if I need to import additional javascript to use json. Because I don't know how to make it work. all i get is undefined. Any help is aprreciated.
The json file:
"hotels": [
{
"name": "Hotel Sunny Palms",
"imgUrl": "imgs/sunny.jpg",
"rating": 5,
"price": 108.00
},
{
"name": "Hotel Snowy Mountains",
"imgUrl": "imgs/snowy.jpg",
"rating": 4,
"price": 120.00
},
{
"name": "Hotel Windy Sails",
"imgUrl": "imgs/windy.jpg",
"rating": 3,
"price": 110.00
},
{
"name": "Hotel Middle of Nowhere",
"imgUrl": "imgs/nowhere.jpg",
"rating": 4,
"price": 199.00
}
]
my javascript is
function hot1(){
var text = '{"hotels": [{"name": "Hotel Sunny Palms","imgUrl": "http://www.pruebaswebludiana.xyz/imgs/sunny.jpg","rating": 5,"price": 108.00}]}';
var obj = JSON.parse(text);
document.getElementById("img-container").innerHTML =
obj.imagUrl+ "<br>"+ obj.name+ " " +obj.rating+ " " +obj.price;}
and my html code is
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2" />
<link rel='stylesheet' href='style.css' type='text/css' media='all' />
</head>
<body>
<nav></nav>
<div class="container">
<div>
<ul>
<li onclick="hot1()">Hotel Sunny Palms</li>
<li onclick="hot2()">Hotel Snowy Mountains</li>
<li onclick="hot3()">Hotel Windy Sails</li>
<li onclick="hot4()">Hotel Middle Of Nowhere</li>
</ul>
</div>
<div class="banner-section" id="img-container">
</div>
</body>
</html>
Your JSON file contains an array in the property hotels, you probably need to work with one of those, e.g.:
var jsonText = ...;
var parsedObject = JSON.parse(jsonText);
var hotels = parsedObject.hotels;
var hotel = hotels[0]; // instead of 0, pass the index of the needed hotel
document.getElementById("img-container").innerHTML =
hotel.imgUrl + "<br/>" + hotel.name + " " + hotel.rating + " " + hotel.price;
{"hotels": [{"name": "Hotel Sunny Palms","imgUrl": "http://www.pruebaswebludiana.xyz/imgs/sunny.jpg","rating": 5,"price": 108.00}]}
You get undefined because you are trying to read the name (and other properties) of the outer object.
The outer object doesn't have those properties. It has one property: hotels.
The value of the property is an array.
That array contains an object.
The properties you are trying to access exist on that object.
i.e.
obj.hotels[0].name // etc
Related
I created a project and I'm trying to add gogocartoJs in it.
The project works but the map is not showing.
I tried with the guides I found in the site, it looks plain and easy, but there is an step that I'm not understanding (please dont just copy/paste a piece of the site like it was obvious what it is the mistake, because it is not for me)
<html lang="en">
<head>
<link
rel="stylesheet"
href="https://gogocarto.fr/assets/css/gogocarto.min.css"
/>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<script type="text/javascript" src="./jquery.js"></script>
<script src="https://gogocarto.fr/js/gogocarto.min.js"></script>
<title>Hello Webpack</title>
</head>
<body>
<div>
<h1>Hello Webpack</h1>
<div id="gogocarto"></div>
</div>
<script>
$(document).ready(function() {
carto = goGoCarto("#gogocarto", {
data: {
taxonomy: taxonomy,
elements: elements
}
});
});
</script>
<script src="./bundle.js"></script>
</body>
</html>
I expect the map to show, and it doesnt
I added the project to github to show better
https://github.com/Aredros/testGogo/tree/master/dist
elements & taxonomy are js variables containing data you must provide according to the format described in the documentation.
// taxonomy
let taxonomy = {
"options":[
{
"id": "eu1",
"name":"Belgium",
"color":"#9acd32",
"icon":"fa-solid fa-building"
},
{
"id": "eu2",
"name": "Netherland",
"color": "#ffa500",
"icon": "fa-solid fa-fan"
},
{
"id": "eu3",
"name": "Luxembourg",
"color": "#a52a2a",
"icon": "fa-solid fa-money-bill-1"
}
]
}
The only missing info in the documentation is the id key in the taxonomy which must be referenced in your elements source dataset.
// elements
let elements = [
{
"title": "Brussels",
"geo": {
"latitude":50.84,
"longitude":4.34
},
"taxonomy": [ "eu1" ],
},
{
"title": "Namur",
"geo": {
"latitude":50.45,
"longitude":4.88
},
"taxonomy": [ "eu1" ],
},
{
"title": "Liege",
"geo": {
"latitude":50.62,
"longitude":5.60
},
"taxonomy": [ "eu1" ],
},
{
"title": "Rotterdam",
"geo": {
"latitude":51.88,
"longitude":4.51
},
"taxonomy": [ "eu2" ],
},
{
"title": "Amsterdam",
"geo": {
"latitude":52.07,
"longitude":5.12
},
"taxonomy": [ "eu2" ],
},
]
Idealy you should build an API returning taxonomy classification & elements data. Then perform ajax call in your html page.
$.ajax({
type: 'GET',
url: '/ajax/url_to_get_elements',
dataType: 'json',
success: function(elements, status) {
build_map(elements);
}
});
// build map = function with 1 arguments (elements) where you put the call to goGoCarto and options...
You can define more than 1 taxonomy group (Example above is about English countries) with the name you want => Cfr. Advanced Taxonomy with Categories. Your elements can then have multiple taxonomy reference listed [ "eu1", "week22", 14 ]. Items in the list can be Integer or String. The only important thing is the ID key and the taxonomy order! Keep the same order in your taxonomy than in your key "taxonomy": in your elements data sources!
Point of attention
Because the library is highly configurable with options, colors and icons it is important to put all your <scripts> tags inside <head> tags of your html page!
When i access this url: http://jservice.io/api/random the output is something like this:
[{
"id": 67917,
"answer": "agua",
"question": "After some fierce flamencoing, you might hear cries of this, Spanish for \"water\"",
"value": 800,
"airdate": "2004-11-18T12:00:00.000Z",
"created_at": "2014-02-11T23:29:50.743Z",
"updated_at": "2014-02-11T23:29:50.743Z",
"category_id": 1145,
"game_id": null,
"invalid_count": null,
"category": {
"id": 1145,
"title": "foreign words \u0026 phrases",
"created_at": "2014-02-11T22:52:16.443Z",
"updated_at": "2014-02-11T22:52:16.443Z",
"clues_count": 115
}
}]
I'm trying to use $.get() to get the data of request:
<html>
<head>
<title>Quiz</title>
<meta charset="utf-8">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
</head>
<body>
</body>
<script>
$.get("http://jservice.io/api/random", function(data, status){
alert("Data: " + data.title + "\nStatus: " + status);
});
</script>
</html>
But the output is this:
Data: undefined
Status: success
There is no data.title.
data is an array.
title is nested under the array element's category.
For this specific response, you'd need (roughly):
data[0].category.title
But if you can get multiple results back, you need to decide what you're actually going to do.
The return was an array. So you have to use
data[0]. Also the title is inside the category object.
Try this.
$.get("http://jservice.io/api/random", function(data, status){
alert("Data: " + data[0].category.title + "\nStatus: " + status);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
The result can also be achieved by accessing the url as json object. Sharing below code for reference.
<html>
<head>
<title>Quiz</title>
<meta charset="utf-8">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
</head>
<body>
</body>
<script>
(function() {
var srcURL = "http://jservice.io/api/random";
$.getJSON( srcURL, {
format: "json"
})
.done(function( data ) {
$.each( data, function( i, item ) {
console.log(item.category.title);
});
});
})();
</script>
</html>
Hello suppose I have a JSON Object
`var books = [{
"Genre": "Sci-fic",
"Name": "Bookname1"
}, {
"Genre": "Sci-fic",
"Name": "Bookname2"
}, {
"Genre": "Non sci-fic",
"Name": "Bookname3"
}, {
"Genre": "Non sci-fic",
"Name": "Bookname4"
}];`
now how I want to show it like
Sci-fic
Bookname1
Bookname2
Non-scific
Bookname3
Bookname3
I am well aware by angular unique property but unique discard the changes I want to segregate data based on similar string in json object
I have tried so far with unique but no luck. Any suggestion please.
You need to apply a filter. 'orderBy' is being provided by angular.js. You can do something like the following to get the expected result :
INDEX.HTML
<!DOCTYPE html>
<html ng-app="plunker">
<head>
<meta charset="utf-8" />
<title>AngularJS Plunker</title>
<script>document.write('<base href="' + document.location + '" />');</script>
<link rel="stylesheet" href="style.css" />
<script data-require="angular.js#1.4.x" src="https://code.angularjs.org/1.4.9/angular.js" data-semver="1.4.9"></script>
<script src="app.js"></script>
</head>
<body ng-controller="MainCtrl">
<div ng-repeat="bookPerGenre in booksToFilter() | filter:filterGenres">
<b>{{bookPerGenre.Genre}}</b>
<li ng-repeat="book in books | filter:{Genre: bookPerGenre.Genre}">{{book.Name}}</li>
</div>
</body>
</html>
APP.JS
var app = angular.module('plunker', []);
app.controller('MainCtrl', function($scope) {
$scope.books = [{
"Genre": "Sci-fic",
"Name": "Bookname1"
}, {
"Genre": "Sci-fic",
"Name": "Bookname2"
}, {
"Genre": "Non sci-fic",
"Name": "Bookname3"
}, {
"Genre": "Non sci-fic",
"Name": "Bookname4"
}];
$scope.booksToFilter = function(){
indexedGenres = [];
return $scope.books;
};
$scope.filterGenres = function(book) {
var genreIsNew = indexedGenres.indexOf(book.Genre) == -1;
if (genreIsNew) {
indexedGenres.push(book.Genre);
}
return genreIsNew;
};
});
You can refer this plnkr
{{ books[0].Genre }}
{{ books[0].Name }}
like arrays books[0] used to access the first element.
I hope this will help!
I guess you also need to use groupBy filter like the following question
How can I group data with an Angular filter?
Something like
<ul ng-repeat="(key, value) in books | groupBy: 'Genre'">
{{ key }}
<li ng-repeat="book in value">
{{ book.Name }}
</li>
</ul>
Try it.
Just learning javascript & html.
I am trying to get a value from some jsonp. This is what is being returned
detail( {
"StatusCode": 0,
"StatusInfo": "Processed and Logged OK",
"PageNumber": 1,
"TotalPageCount": 1,
"TotalProductCount": 1,
"PageProductCount": 1,
"Products":
[
{
"BaseProductId": "57543094",
"EANBarcode": "5010204736716",
"CheaperAlternativeProductId": "",
"HealthierAlternativeProductId": "",
"ImagePath": "http://img.tesco.com/Groceries/pi/716/5010204736716/IDShot_90x90.jpg",
"MaximumPurchaseQuantity": 99,
"Name": "Tesco Bacon Leek Quiche 400G",
"OfferPromotion": "Any 2 for £4.00",
"OfferValidity": "valid from 2/1/2014 until 21/1/2014",
"OfferLabelImagePath": "http://www.tesco.com/Groceries/UIAssets/I/Sites/Retail/Superstore/Online/Product/pos/2for.png",
"ShelfCategory": "134",
"ShelfCategoryName": "Pies Quiche & Pasties",
"Price": 2.3,
"PriceDescription": "£0.58 each",
"ProductId": "255163145",
"ProductType": "QuantityOnlyProduct",
"UnitPrice": 0.575,
"UnitType": "100g"
}
]
} )
My code is as follows:
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Tesco JSONP</title>
</head>
<body>
<button id="detail">detail</button>
<script type="text/javascript">
function detail(data) {
document.getElementById('name').innerHTML = (data.Products.Name)
}
function data() {
var script_elem = document.createElement('script'),
url = "http://www.techfortesco.com/groceryapi_b1/restservice.aspx?command=PRODUCTSEARCH&JSONP=detail&searchtext=5010204736716&page=1&sessionkey=123456789"
script_elem.setAttribute('src', url);
document.head.appendChild(script_elem);
}
document.getElementById('detail').addEventListener('click', data, false);
</script>
<div id="name"></div>
</body>
</html>
When run I am getting undefined. I'm guessing that my syntax (data.Products.Name) is incorrect. If I try (data.StatusCode) then I get the correct result.
Can someone please advise.
Best wishes.
data.Products is an array.
You need to specify which element you want to acess in the array.
In this case you only have one element, so the correct syntax would be data.Products[0].name
Here is the Live Example what I currently have now : https://dl.dropboxusercontent.com/u/11126587/input%20Tag%20Creation/tag.html
What I am wanting is that if I click on the "+ Add Another Segment" text it will Create same input box with same tag effect Like what currently have now(You can write Something and press the Enter To See the Tag Effect) .
HTML
<html>
<head>
<meta charset="utf-8">
<title>
Input Tag
</title>
<link rel="StyleSheet" href="css/jquery.tagedit.css" type="text/css" media="all"/>
<script type="text/javascript" src="js/jquery-1.7.1.js"></script>
<script type="text/javascript" src="js/jquery-ui-1.8.6.custom.min.js"></script>
<script type="text/javascript" src="js/jquery.autoGrowInput.js"></script>
<script type="text/javascript" src="js/jquery.tagedit.js"></script>
<script type="text/javascript">
$(function() {
// Empty List
$( '#empty-list input.tag' ).tagedit({
autocompleteURL: 'server/autocomplete.php'
});
// Edit only
$( '#brackets input.tag').tagedit({
autocompleteURL: 'server/autocomplete.php'
});
// Arrow List
$( '#arrow input.tag' ).tagedit({
autocompleteURL: 'server/autocomplete.php',
autocompleteOptions: {minLength: 0}
});
// Custom Break Characters
$('#custom-break input.tag').tagedit({
autocompleteURL: 'server/autocomplete.php',
// return, comma, space, period, semicolon
breakKeyCodes: [ 13, 44, 32, 46, 59 ]
});
// Local Source
var localJSON = [
{ "id": "1", "label": "Hazel Grouse", "value": "Hazel Grouse" },
{ "id": "2", "label": "Common Quail", "value": "Common Quail" },
{ "id": "3", "label": "Greylag Goose", "value": "Greylag Goose" }
];
$('#local-source input.tag').tagedit({
autocompleteOptions: {
source: localJSON
}
});
$('#local-source2 input.tag').tagedit({
autocompleteOptions: {
source: localJSON
}
});
$('#local-source3 input.tag').tagedit({
autocompleteOptions: {
source: localJSON
}
});
// Function Source
$('#function-source input.tag').tagedit({
autocompleteOptions: {
source: function(request, response){
var data = [
{ "id": "1", "label": "Hazel Grouse", "value": "Hazel Grouse" },
{ "id": "2", "label": "Common Quail", "value": "Common Quail" },
{ "id": "3", "label": "Greylag Goose", "value": "Greylag Goose" },
{ "id": "4", "label": "Merlin", "value": "Merlin" },
];
return response($.ui.autocomplete.filter(data, request.term) );
}
}
});
});
</script>
</head>
<body>
<p id="local-source" style="padding:0px; margin:0px;">
<input type="text" name="tag[]" value="" class="tag"/>
</p>
+ Add Another Segment
I found this tag Effect from a someones Blog But I wanted to extend this with Click to Create New Segment . Also I am not used to with js Fiddle So I gave example link from my Drop Box .
If Someone can make this it would be great . If my posting format have anything Wrong please let me know if I Can help you with posting or giving more Information .
Thanks in advance
Something like this??
<p id="local-source">
<input type="text" class="tag"/>
</p>
<div id="add">
+ Add Another Segment
</div>
$(document).ready(function() {
$('#add').on('click', function() {
var input = '<input type="text" class="tag"/>';
$(input).appendTo($('#local-source'));
});
});