dynatable not creating table from remote JSON - javascript

Here's feature-table.JSON in the same directory as the HTML file:
[
{
"band": "Weezer",
"song": "El Scorcho"
},
{
"band": "Chevelle",
"song": "Family System"
}
]
Here's my HTML file:
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="jquery-1.11.1.min.js">
<script type="text/javascript" src="jquery.dynatable.js"></script>
<script type="text/javascript">
$.getJSON("feature-table.JSON", function(data) {
alert(data);
$("#feature-table").dynatable({
dataset: {
records: data
}
});
});
</script>
</head>
<body>
<table id="feature-table">
<thead>
<th>band</th>
<th>song</th>
</thead>
<tbody>
</tbody>
</table>
</body>
</html>
The alert pops up with the correct JSON data so i know it's finding it. I've tried: version 2 of jQuery, uploading and using URLs of the js files to make sure the files are in the right place, $.ajax but then $.getJSON after reading Load remote JSON from Dynatable, and various other things. I'm out of ideas. What am I overlooking?

I discovered I needed to have my JavaScript inside $(document).ready(function(){...}).

Hope this helps.
Did you also include the metadata as per the documentation for the JSON array.
{
"records": [
{
"someAttribute": "I am record one",
"someOtherAttribute": "Fetched by AJAX"
},
{
"someAttribute": "I am record two",
"someOtherAttribute": "Cuz it's awesome"
},
{
"someAttribute": "I am record three",
"someOtherAttribute": "Yup, still AJAX"
}
],
"queryRecordCount": 3,
"totalRecordCount": 3
}

Related

Access json data from external file

I am trying to load/read data from a local json file using JQuery/Javascript. Everything I have tried so far is throwing me CORS policy error. I don't know how to resolve this.
<html>
<body>
<div>
Fetch JSON
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
$(function() {
$('#fetch').click(function() {
$.getJSON('music.json', function(data) {
albums = data['Albums']
console.log(albums)
})
});
})
</script>
</body>
</html>
Json file -
{
"Albums": [{
"albumName": "Desire",
"artist": "Bob Dylan"
},
{
"albumName": "Live in London",
"artist": "Leonard Cohen"
},
{
"albumName": "Abbey Road",
"artist": "The Beatles"
},
{
"albumName": "Blackstar",
"artist": "David Bowie"
}
]
}
How to get this running?
You should run your project on the web server, in this case, you can do this:
data.json
{
"albums": [
{
"name": "First Album",
"artist": "Leonard Cohen"
}
]
}
in html or js file:
fetch('http://127.0.0.1:5500/data.json')
.then(response => response.json())
.then(json => console.log(json))
in this case, my webserver local address is http://127.0.0.1:5500

JSON - Invalid Token

I watched a YouTube video trying to learn JSON for the first time. This is the example we did during the video, but at '[ I get an Invalid Token error when looking at the console. Sorry for the noob question! Thanks again.
<html>
<head>
<title>JSON Example</title>
</head>
<body>
<script type="text/javascript">
let companies =
'[
{
"name": "Big Corporation",
"numberOfEmployees": 10000,
"ceo": "Mary",
"rating": 3.6
},
{
"name": "Small Startup",
"numberOfEmployees": 3,
"ceo": null,
"rating": 4.3
}
]'
console.log(JSON.parse(companies))
((companies)[0].name)
</script>
</body>
</html>
The problem is not a JSON one but a JavaScript one. You have to use a particular syntax for multiline strings in JavaScript.
There are multiple ways of doing this but probably the simplest is to use backticks.
<html>
<head>
<title>JSON Example</title>
</head>
<body>
<script type="text/javascript">
let companies =
`[
{
"name": "Big Corporation",
"numberOfEmployees": 10000,
"ceo": "Mary",
"rating": 3.6
},
{
"name": "Small Startup",
"numberOfEmployees": 3,
"ceo": null,
"rating": 4.3
}
]`
console.log(JSON.parse(companies))
((companies)[0].name)
</script>
</body>
</html>
PS: As an aside you'll also get an error on the last line ((companies)[0].name) because the output of console.log isn't a function. Presumably you want another call to console.log

How to use single json file to consume in alpacajs

I have created a simple form using alpacajs, as per the documentation provided by alpacajs.org we can use properties such as optionsSource, schemaSource, viewSource, dataSource for loading the external json files into our application. But what i need is i need to use only one json file for all these. I mean instead of using all these 3 different properties can i use only one parameter for loading the single json file which comes from the backend. please check my code below..
<html>
<head>
<meta charset="UTF-8">
<title>My Little Alpaca Form</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/handlebars.js/4.0.5/handlebars.min.js"> </script>
<script src="https://code.jquery.com/jquery-1.12.4.min.js" integrity="sha256-ZosEbRLbNQzLpnKIkEdrPv7lOy9C27hHQ+Xp8a4MxAQ=" crossorigin="anonymous"></script>
<script src="//code.cloudcms.com/alpaca/1.5.22/bootstrap/alpaca.min.js"></script>
<!-- typeahead.js https://github.com/twitter/typeahead.js -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/typeahead.js/0.10.5/bloodhound.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/typeahead.js/0.10.5/typeahead.bundle.min.js"></script>
<link href="//code.cloudcms.com/alpaca/1.5.22/bootstrap/alpaca.min.css" rel="stylesheet" />
<link type="text/css" href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap.min.css" rel="stylesheet"/>
</head>
<body>
<div id="form1"></div>
<script type="text/javascript">
$(document).ready(function() {
$("#form1").alpaca({
"dataSource": "/fulfiller/connector-custom-data.json",
"schemaSource": "/fulfiller/connector-custom-schema.json",
"optionsSource": "/fulfiller/connector-custom-options.json",
"viewSource": "/fulfiller/connector-custom-view.json",
"view": {
"parent": "bootstrap-edit",
"layout": {
"template": "threeColumnGridLayout",
"bindings": {
"requestedfor": "column-1",
"location": "column-2",
"shortdescription": "column-3",
"description": "column-3",
}
},
"templates": {
"threeColumnGridLayout": '<div class="row">' + '{{#if options.label}}<h2>{{options.label}}</h2><span></span>{{/if}}' + '{{#if options.helper}}<p>{{options.helper}}</p>{{/if}}' + '<div id="column-1" class="col-md-6"> </div>' + '<div id="column-2" class="col-md-6"> </div>' + '<div id="column-3" class="col-md-12"> </div>' + '<div class="clear"></div>' + '</div>'
}
},
"options": {
"fields": {
"requestedfor": {
"type": "text",
"id": "requestedfor",
"label": "*Requested For",
"typeahead": {
"config": {},
"datasets": {
"type": "remote",
"displayKey": "value",
"templates": {},
"source": "http://www.alpacajs.org/data/tokenfield-ajax1.json"
}
}
},
"location": {
"type": "text",
"label": "*Location"
},
"shortdescription": {
"type": "text",
"label": "Short Description"
},
"description": {
"type": "textarea",
"rows": 5,
"cols": 40,
"label": "Description"
}
},
"form": {
"attributes": {
"action": "#",
"method": "post"
},
"buttons": {
"submit": {
"value": "Submit",
"class": "btn btn-default"
}
}
}
}
});
});
</script>
</body>
</html>
So here in the above code i have used these urls for loading json data..
"dataSource": "/fulfiller/connector-custom-data.json"
"schemaSource": "/fulfiller/connector-custom-schema.json"
"optionsSource": "/fulfiller/connector-custom-options.json"
"viewSource": "/fulfiller/connector-custom-view.json"
So instead of using these 3 different properties can i use only one property like "oneSingleJSONSource": "oneJSONRemoteFile.json"
Can anybody provide inputs?
For Alpaca to be inialized it must have a DOM element + a config object that contains the schema, options and other properties that Alpaca already knew in its core code, so in your case this is possible if you try to modify the alpaca core code... If your objective is only to optimize resource loading you can use only one json file that contains all the configuration and input them in the alpaca initialization $(dom).alpaca(_json_data_from_loaded_file). And if you want to have only schema, options and view settings in on file you should divide the data loaded to 3 objects, 1 for schema, 1 for options and the last one for view settings.
Tell me if you want more details on achieving this.
I'll be glad to help.

Dynatable Implementation

I am attempting to learn some jQuery and javascript and have a neat project to try. It involves pulling data from a JSON file and displaying it in a table form, based on date. I've found Dynatable which seems to do what I want, but I keep getting an "unexpected end of JSON input" error. I am using the same syntax as in the example given on the Dynatabe page, but it does not return any records. Any help would be appreciated, as I'm sure I'm missing something simple. The JSON file is named json-records.json
[
{
"band": "Weezer",
"song": "GA Scorcho"
},
{
"band": "Chevelle",
"song": "Family System"
},
]
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<script src="./jspkg-archive/jquery.dynatable.js"></script>
<script src="json-records.json"></script>
<style src="./jspkg-archive/jquery.dynatable.css"></style>
</head>
<body>
<table id="my-final-table">
<thead>
<th>Band</th>
<th>Song</th>
</thead>
<tbody>
</tbody>
</table>
<script type="text/javascript">
$(document).ready( function(){
$('#my-final-table').dynatable();
});
var $records = $('#json-records'),
myRecords = JSON.parse($records.text());
$('#my-final-table').dynatable({
dataset: {
records: myRecords
}
});
</script>
</body>
</html>
You have a stray ',' in your JSON file
[
{
"band": "Weezer",
"song": "GA Scorcho"
},
{
"band": "Chevelle",
"song": "Family System"
}, <--- Here
]

Parse local JSON file with jQuery and Javascript

I'm trying to parse a JSON file located on my computer. I want to parse it. The JSON file has this structure:
{
"sites": {
"site": [
{
"id": "01",
"name": "Sito 1",
"src": "localhost/root/coupon/sito1",
"expiryDate": "29 Ago 2013"
},
{
"id": "02",
"name": "Sito 2",
"src": "localhost/root/coupon/sito2",
"expiryDate": "30 Ago 2013"
},
{
"id": "Sito 3",
"name": "Sito 3",
"src": "localhost/root/coupon/sito2",
"expiryDate": "31 Ago 2013"
}
]
}
}
In my html I import the jQuery library and I made a function that will load when the page is loaded. The code is below:
<!DOCTYPE html>
<html lang="it">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width; initial-scale=1.0; maximum-scale=1.0; user-scalable=0;"/>
<title>Lista coupon</title>
<script type="text/javascript" src="jquery-1.9.1.min.js"></script>
<script type="text/javascript" charset="utf-8">
function loadJson() {
window.alert("Carico il contenuto del file JSON per popolare la lista");
$(document).ready(function()
{
$.getJSON('data.json', function(json) {
console.log(json);
});
});
}
</script>
</head>
<body onload="loadJson();">
<div id="header">
<h1>Lista coupon salvati</h1>
</div>
<div id="content">
<p>Di seguito trovi tutte le promozioni salvate</p>
</div>
<div id="footer">
</div>
</body>
</html>
Now I saw on firebug console that it can read correctly the JSON file, but I don't know how to parse this JSON. I searched in google, but I found a lot of example that use a remote JSON. Can you help me to understand how to parse a local JSON file?
Thank you
PS: note the site I post on here it's made for mobile browser.
getJSON will parse it for you.
Just remove the var obj = $.parseJSON(json); line (since that will stringify the object and try to parse it as JSON (which it won't be)).
I don't think you need to parse the json. It will automatically parse the json since you are using $.getJSON().

Categories

Resources