Im taking my first steps in json.
There is a huge database where you can query all kinds of statistics regarding my country. Like population
http://px.hagstofa.is/pxen/pxweb/en
Now, if you surf the link above to say population you end up here :
http://px.hagstofa.is/pxen/pxweb/en/Ibuar/Ibuar__mannfjoldi__1_yfirlit__arsfjordungstolur/MAN10001.px/?rxid=f4a21b41-fb7a-45dc-9aec-62ae2d3cea5c
If you select some options you get here :
http://px.hagstofa.is/pxen/pxweb/en/Ibuar/Ibuar__mannfjoldi__1_yfirlit__arsfjordungstolur/MAN10001.px/table/tableViewLayout1/?rxid=f4a21b41-fb7a-45dc-9aec-62ae2d3cea5c
Click the About table and then click "Make this table available in your application"
Now you see a url for posting to json and the json query......
Ive been trying now for few hours to get any kind of data from this url, but I just cant seem to dig it out.
I tried something like this :
<!DOCTYPE HTML>
<html lang="en-US">
<head>
<meta charset="UTF-8">
<title>JSON Tutorial</title>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.7.2.min.js"></script>
</head>
<body>
<script type="text/javascript">
$.getJSON('http://px.hagstofa.is/pxis/api/v1/is/Ibuar/mannfjoldi/2_byggdir/sveitarfelog/MAN02001.px', function(data) {
console.log(data.variables)
})
</script>
</body>
</html>
Which gave me the next objects.. But I cannot figure out how to get some statistics.....
for example :
female population in 2015
Any help is very much needed.
EDIT :
Few hours later , im still stuck, but im up to this code now :
<!DOCTYPE HTML>
<html lang="en-US">
<head>
<meta charset="UTF-8">
<title>JSON Tutorial</title>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.7.2.min.js"></script>
</head>
<body>
<script type="text/javascript">
$.ajax({
url: 'http://px.hagstofa.is/pxis/api/v1/is/Ibuar/mannfjoldi/2_byggdir/sveitarfelog/MAN02001.px',
dataType: 'json',
type: 'get',
cache: false,
success: function(data) {
$(data.variables).each(function(index, value) {
console.log(value.values.Alls + ' test ' + value.values );
document.write(value.values[0] + '<br>');
});
}
});
</script>
</body>
</html>
Best regards
The data.variables is an array of four objects. Each object contains four properties, among which are valueTexts and values. So you need a first loop for the first array of four objects, then another loop to find the valueTexts / values pairs:
$.getJSON('http://px.hagstofa.is/pxis/api/v1/is/Ibuar/mannfjoldi/2_byggdir/sveitarfelog/MAN02001.px', function(data) {
console.log (data.variables);
for( let i = 0; i < data.variables.length; i++ ){
console.info( data.variables[i].text );
for( let k = 0; k < data.variables[i].valueTexts.length; k++ ){
console.log( data.variables[i].valueTexts[k] + ' ' + data.variables[i].values[k] );
}
}
});
Below is a working solution for my question :
There is probably a better way to do this , but I needed a query for the POST, and that gave me results.
Now I just need to make this code spit out the results in csv or xml file.
If anyone has a solution for that , i'd be very thankful.
<html lang="en">
<meta charset="utf-8">
<head>
<script type="text/javascript" src="https://code.jquery.com/jquery-2.1.4.min.js"></script>
</head>
<script>
var query = {
"query": [
{
"code": "Sveitarfélag",
"selection": {
"filter": "item",
"values": [
"Alls"
]
}
},
{
"code": "Aldur",
"selection": {
"filter": "item",
"values": [
"Alls"
]
}
},
{
"code": "Ár",
"selection": {
"filter": "item",
"values": [
"18"
]
}
},
{
"code": "Kyn",
"selection": {
"filter": "item",
"values": [
"Alls"
]
}
}
],
"response": {
"format": "csv"
}
};
query = JSON.stringify(query);
$.ajax({
type: "POST",
url: "http://px.hagstofa.is/pxis/api/v1/is/Ibuar/mannfjoldi/2_byggdir/sveitarfelog/MAN02001.px",
data:query,
success: function(json) {
document.write(json);
}
});
</script>
</html>
Related
I am attempting to create a datatable where the user can filter the table using dropdown menus. The first dropdown menu "project_select" fills with all the unique values from a column of the data table. The second dropdown menu "hr_select" fills with values based on the user's selection from the "project_select" dropdown menu.
Currently, the dropdown menus are mapped to span elements in the html. I am looking to convert these span elements to select2.
This is my desired html code:
<label for="project_select"></label><select id="project_select" class="js-example-basic-single" style="width: 10%">
<option></option>
</select>
<label for="hr_select"></label><select id="hr_select" class="js-example-basic-multiple" multiple="multiple" style="width:15%">
<option></option>
</select>
However, when I try and replace the span elements with that desired HTML code.. it doesn't work.
This is my code: https://jsfiddle.net/dfahsjdahfsudaf/nL6q21g9/16/
Thanks in advance for any help!
I converted my comments to an answer for future visitors to this question:
The steps needed to convert your standard selects to "Select2" selects are:
Add the required libraries to the page:
<link href="https://cdn.jsdelivr.net/npm/select2#4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" />
<script src="https://cdn.jsdelivr.net/npm/select2#4.1.0-rc.0/dist/js/select2.min.js"></script>
Give IDs to each of the current <select> elements:
select = $('<select id="project_s2"><option value=""></option></select>');
and:
select = $('<select id="hr_s2" multiple><option value=""></option></select>');
Use those IDs to initialize Select2:
$('#project_s2').select2();
$('#hr_s2').select2();
The end result is:
var dataSet = [{
"Project_Name": "A",
"ID": "65",
"HR": "0",
},
{
"Project_Name": "A",
"ID": "65",
"HR": "10",
},
{
"Project_Name": "B",
"ID": "65",
"HR": "0",
},
{
"Project_Name": "B",
"ID": "65",
"HR": "20",
},
{
"Project_Name": "C",
"ID": "65",
"HR": "20",
},
{
"Project_Name": "C",
"ID": "65",
"HR": "100",
},
];
$(document).ready(function() {
var table = $('#example').DataTable({
data: dataSet,
orderCellsTop: true,
columns: [{
data: "Project_Name"
},
{
data: "ID"
},
{
data: "HR"
}
],
initComplete: function() {
this.api().columns([0, 2]).every(function() {
var column = this;
var colIdx = column.index();
var node;
var select;
if (colIdx === 0) {
node = $('#project_select');
select = $('<select id="project_s2" style="width: 40%"><option value=""></option></select>');
} else {
node = $('#hr_select');
select = $('<select id="hr_s2" style="width: 20%" multiple><option value=""></option></select>');
}
select.appendTo($(node).empty())
.on('change', function() {
var val = $(this).val();
if (colIdx === 0) {
val = $.fn.dataTable.util.escapeRegex(val);
column.search(val ? '^' + val + '$' : '', true, false).draw();
rebuildPositionSelect();
} else {
var vals = val.map(x => $.fn.dataTable.util.escapeRegex(x)).join('|');
column.search(vals ? '^' + vals + '$' : '', true, false).draw();
}
});
column.data().unique().sort().each(function(val) {
select.append('<option value="' + val + '">' + val + '</option>')
});
});
$('#project_s2').select2();
$('#hr_s2').select2();
}
});
function rebuildPositionSelect() {
var select = $('#hr_select select').empty().append('<option value=""></option>');
var column = table.column(2, {
search: 'applied'
});
column.search('').draw();
column.data().unique().sort().each(function(val) {
select.append('<option value="' + val + '">' + val + '</option>');
});
}
});
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>Demo</title>
<script src="https://code.jquery.com/jquery-3.5.1.js"></script>
<script src="https://cdn.datatables.net/1.10.22/js/jquery.dataTables.js"></script>
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.22/css/jquery.dataTables.css">
<link rel="stylesheet" type="text/css" href="https://datatables.net/media/css/site-examples.css">
<link href="https://cdn.jsdelivr.net/npm/select2#4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" />
<script src="https://cdn.jsdelivr.net/npm/select2#4.1.0-rc.0/dist/js/select2.min.js"></script>
</head>
<body>
<div style="margin: 20px;">
<div>
<span>Project: </span>
<span id="project_select"></span>
<span> HR: </span>
<span id="hr_select"></span>
</div>
<br><br>
<table id="example" class="display dataTable cell-border" style="width:100%">
<thead>
<tr>
<th>Project_Name</th>
<th>ID</th>
<th>HR</th>
</tr>
</thead>
</table>
</div>
</body>
</html>
As mentioned in the comments, this is a very basic set-up for each Select2 drop-down.
To customize them further you can provide options - for example:
$('#project_s2').select2( {
theme: "classic",
placeholder: 'Select an option'
} );
Final Note:
The use of basic <span> elements in the above example, only minimal layout/styling may be insufficient for your needs. So, you will probably want to provide CSS customizations which provide a better overall layout. But those changes should not affect your Select2 elements.
For example, adding in style="width: 40%" (as shown above) makes a difference - but that may not be what you want, in your specific case.
I want to test my ajax 'PUT' function when passing a parameter 1 but it returned undefined??
orders.json
[
{
"id" : 1,
"name": "will_1",
"drink" : "cola_2"
},
{
"id" : 2,
"name": "Laura",
"drink" : "vanilla"
}
]
$(document).ready(function(){
$("#purchaseId").change(function() {
$.ajax({
type:'POST',
url:'orders.json',
data: "1",
success:function(newOrder) {
alert(newOrder.name);
},
error:function(){
alert("loading error");
}
});
});
});
<html lang="en">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src="home.js">
</script>
<title>Javascript on Steroids</title>
</head>
<body>
<select id = "purchaseId" >
<option value="1" selected >1</option>
<option value="2">2</option>
</select>
</body>
</html>
When you POST or PUT, you are sending data: "1", which only sends the parameter, but not it's value.. In GET it would look like: //someurl/?1=
Try: data: "order=1", which will POST/PUT a parameter: order with value: 1
This way on the backend you can expect the $_POST['order'], and will grab its sent value of 1
$.post("getdata.php",{
id:productId
}, function(data,status){
$("#result").html(data);
});
Please help. I'm unable to match JSON parsed values to customer name using Data tables. I was able to populate table column with contact info, but parsed data is identical for both accounts in the table created by code shown. Is there a better way to loop through the data so it displays correctly.
I've seen a few examples of doing this with a simple table, but I would like to keep the sorting capability of Data Tables if possible. Any help will be greatly appreciated.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Table 01</title>
</head>
<body>
<link href="https://cdn.datatables.net/1.10.19/css/jquery.dataTables.min.css" rel="stylesheet"/>
<script src="https://code.jquery.com/jquery-3.3.1.js"></script>
<script src="https://cdn.datatables.net/1.10.19/js/jquery.dataTables.min.js"></script>
<table id="tableId" class="table table-condensed responsive"></table>
</body>
<script>
var data01 = [
{
"name": "EXAMPLE Mickey",
"due": "2018-11-22T19:00:00.000Z",
"labels": [
{
"name": "Salesperson_1",
"color": "green"
}
],
"pluginData": [
{
"value": "{\"billContact\":\"Mickey Mouse\",\"billCompany\":\"MM Clubhouse\"}",
"access": "shared"
}
]
},
{
"name": "EXAMPLE Carl",
"due": "2018-11-25T19:00:00.000Z",
"labels": [
{
"name": "Salesperson_2",
"color": "yellow"
}
],
"pluginData": [
{
"value": "{\"billContact\":\"Carl Grimes\",\"billCompany\":\"Rick's Group\"}",
"access": "shared"
}
]
}
];
$('#tableId').DataTable({
data: data01,
"columns": [
{"data": "name"},
{"data": "due"},
{"data": "labels.0.name"},
{"data": "pluginData.0.value"},
{"data": function(){
for (var i=0; i < data01.length; i++){
var values = data01[i].pluginData[0].value;
var parsedVal = JSON.parse(values);
var contact = parsedVal.billContact;
return contact;
//console.log(contact);
}
}}
]
});
</script>
</html>
When you pass a function to a column, an argument is passed to that function which represents one entry of your data. So there is no need to iterate over your data by yourself, jQuery is doing that for you.
$('#tableId').DataTable({
data: data01,
"columns": [
{"data": "name"},
{"data": "due"},
{"data": "labels.0.name"},
{"data": "pluginData.0.value"},
{"data": function (row){
let values = row.pluginData[0].value;
let parsedVal = JSON.parse(values);
let contact = parsedVal.billContact;
return contact;
}}
]
});
If you do the iteration by yourself, the function will terminate at the return statement. So everytime the function is called it just see the first entry and return it and stop at that point.
file snapshot_report_js.js:
require([
"dojo/dom",
"dojo/json",
"dojo/store/Memory",
"dijit/tree/ObjectStoreModel",
"dijit/Tree",
"dojo/text!http://localhost:8080/dojo/json_data/snapshot.json",
"dojo/domReady!",
"dojo/_base/json"
], function(dom, json, Memory, ObjectStoreModel, Tree, small){
var stringfied_content = JSON.stringify(small)
var json_parsed_data = JSON.parse(stringfied_content, true)
var json_data = dojo.toJson(json_parsed_data);
// set up the store to get the tree data
var json_store = new Memory({
data: [ json_data ],
getChildren: function(object){
return object.children || [];
}
});
// Create the model
var snapshot_treeModel = new ObjectStoreModel({
store: json_store,
query: {id: 'snapshot'}
});
var snapshot_tree = new dijit.Tree({
model: snapshot_treeModel
}, 'div_snapshot_tree');
snapshot_tree.startup();
})
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Snapshot</title>
<link rel="stylesheet" href="dijit/themes/claro/claro.css">
<!-- load Dojo -->
<script src="dojo/dojo.js" data-dojo-config="async: true"></script>
<script src="js/snapshot_report_js.js"></script>
</head>
<body class="claro">
<div id="div_snapshot_tree"></div>
</body>
</html>
JSON file:
{
"snapshot_metadata": {
"report_end_at": "2017-10-11 02:03:36",
"environment_name": "DVINST",
"report_start_at": "2017-10-11 01:55:42"
},
"versions": [
{
"id": "version_001",
"instances": [
{
"instance_name": "instance1",
"instance_create_date": "2017-09-18 00:17:52",
"connected_site_count": 4,
"admin_server": "t3://tserver:18300",
"instance_id": 2411,
"instance_type": "OSVC",
"instance_created_by": "None",
"site_capacity": 2,
"sites": [
{
"site_db_id": 395,
"site_name": "zzzz_178",
"site_users": "uc1,uc2,uc3",
"site_id": 89492,
"site_owner": "owner1",
"site_db_name": "site_server2"
},
{
"site_db_id": 395,
"site_name": "site2",
"site_users": "u1, u2, u3",
"site_id": 90447,
"site_owner": "u2",
"site_db_name": "site_server3"
}
]
}
]
}
],
"servers": [
{
"status": null,
"server_id": 13,
"server_name": "db1",
"server_type": "database",
"mount_points": [],
"sites": [],
"db_connections_count": 6,
"health": null,
"admin_servers": null,
"db_sites_connected_count": null
}
]
}
Error on console:
dojo.js:8 Uncaught Error: dijit.tree.ObjectStoreModel: root query
returned 0 items, but must return exactly one at Object.
(ObjectStoreModel.js.uncompressed.js:86) at dojo.js:8 at when
(dojo.js:8) at Object.getRoot
(ObjectStoreModel.js.uncompressed.js:82) at Object._load
(Tree.js.uncompressed.js:897) at Object.postCreate
(Tree.js.uncompressed.js:844) at Object.create
(_WidgetBase.js.uncompressed.js:453) at Object.postscript
(_WidgetBase.js.uncompressed.js:366) at new (dojo.js:8)
at snapshot_report_js.js:178
I don't see anything wrong here, can anybody help?
At first glance your ObjectStoreModel is trying to find root object for tree and as you specified it should have property id equals to snapshot; nothing in your JSON is matching that query.
Secondly, JSON data should bring tree-structured content while your JSON is unstructured; see ObjectStoreModel example how tree data looks like. If you have custom data structure then you need to transform it to be consumed by tree widget thru its model.
I am running this code and getting nothing in output. There is no error in the buildup but I am not able to find out the mistakes. Can anyone tell me what could be the issue?? Regards
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<script src="Dependencies/Angular/angular.js"></script>
<script src="Dependencies/D3/d3.js"></script>
<script src="Dependencies/nvd3/nv.d3.js"></script>
<script src="Dependencies/Angularjs-nvd3-Directives/angularjs-nvd3-directives.js"></script>
<link rel="stylesheet"href="Dependencies/nvd3/nv.d3.css">
<script>
var app = angular.module("nvd3TestApp", ['nvd3ChartDirectives']);
function ExampleCtrl($scope){
$scope.exampleData = [
{
"key": "Series 1",
"values": [ [ 1025409600000 , 0] , [ 1309406400000 , 121.92388706072] , [ 1312084800000 , 116.70036100870] , [ 1314763200000 , 88.367701837033] , [ 1317355200000 , 59.159665765725] , [ 1320033600000 , 79.793568139753] , [ 1322629200000 , 75.903834028417] , [ 1325307600000 , 72.704218209157] , [ 1327986000000 , 84.936990804097] , [ 1330491600000 , 93.388148670744]]
}];
}
</script>
</head>
<body ng-app='nvd3TestApp'>
<div ng-controller="ExampleCtrl">
<nvd3-line-chart data="exampleData"
showXAxis="true"
showYAxis="true"
tooltips="true"
interactive="true">
</nvd3-line-chart>
</div>
</body>
</html>
I believe I have solved your issue with your code. I didn't load any css so you may have to add yours to make it look right. I would also move your script tags to right before the closing </body> tag. That way your code will not run before the dom loads. This will prevent some headaches in the future.
Live Preview: http://codepen.io/larryjoelane/pen/OMQqMd
JavaScript/Angular Code:
var app = angular.module("nvd3TestApp", ['nvd3ChartDirectives']).controller("ExampleCtrl", function($scope) {
$scope.exampleData = [{
"key": "Series 1",
"values": [
[1025409600000, 0],
[1309406400000, 121.92388706072],
[1312084800000, 116.70036100870],
[1314763200000, 88.367701837033],
[1317355200000, 59.159665765725],
[1320033600000, 79.793568139753],
[1322629200000, 75.903834028417],
[1325307600000, 72.704218209157],
[1327986000000, 84.936990804097],
[1330491600000, 93.388148670744]
]
}];
})();
Global functions as controllers haven't been supported in angular for quite a while ... since around 1.2xx
try
var app = angular.module("nvd3TestApp", ['nvd3ChartDirectives']);
app.controller('ExampleCtrl', function($scope) {
$scope.exampleData = [{
"key": "Series 1",
"values": [
......
]
}];
});