Using AJAX to retrieve data from JSON File - javascript

so I am trying to read the data from my JSON file and display it on the webpage using HTML. It would work with simple keys with this particular database it wouldn't work for me.
JSON:
var carInfo = [
{
carId: 1,
carPrice : 15.00,
},
{
carId: 2,
carPrice : 25.00,
}
];
JS:
$(document).ready(function() {
$.getJSON("vehicle_data.json", function(data) {
$.each(data.carInfo, function() {
$("ul").append("<li>Car ID: "+this[carInfo[0].carId]);
});
});
});
HTML:
<html>
<body>
<ul></ul>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src="json_data_retrieve.js"></script>
</body>
</html>

It is not a valid JSON file. It is a JS script.
var carInfo = [
{
carId: 1,
carPrice : 15.00,
},
{
carId: 2,
carPrice : 25.00,
}
];
Try this:
{
"carInfo":
[
{
"carId": 1,
"carPrice": 15
},
{
"carId": 2,
"carPrice": 25
}
]
}
Update:
You may load this script as a script source in an HTML. It must be an .js file.
<script src="vehicle_data.js"></script>
If you need to load it dynamically, use jQuery $.getScript method.
It doesn't matter that it has .json extensions because it will be evaluated as a script.
$(document).ready(function()
{
$.getScript("vehicle_data.json", function()
{
// Pay attention. In this case, you work with carInfo
// variable because it has been executed as a script,
// but not loaded as a JSON file.
$.each(carInfo, function() {
$("ul").append("<li>Car ID: " + this[carInfo[0].carId]);
});
});
});
However, it is very strange that someone gives you .json file with JS declaration and tells you that you should execute it but shouldn't rename it or load as a script.

Looks like you are trying to iterate the parent object from within itself.
Try this
$.each(data.carInfo, function(k, v) {
$("ul").append("<li>Car ID: "+v.carId);
});

Related

Tags Input With Autocomplete from array in url

I download this script https://www.jqueryscript.net/form/Tags-Input-Autocomplete.html and i create route
Route::get('/ingredients-data', function(){
$data = Menu_Ingredient::all()->pluck('name')->toArray();
return response($data);
});
i wanna use this to source in autocomplete.
<script type="text/javascript">
$(function() {
$('#form-tags-4').tagsInput({
'autocomplete': {
source: [
'apple',
'banana',
'orange',
'pizza'
]
}
});
});
</script>
how i can do it to link route in source?
you should pass your data as encoded json to source :
<script type="text/javascript">
$(function() {
$('#form-tags-4').tagsInput({
'autocomplete': {
source: #json($data)
}
});
});
</script>
You might also like to use the select2 in jquery. Ive used this select2, it has good documentation. You can check their documentation here Select2

Having trouble retrieving custom attribute from HTML Option. Getting back [object Object] instead

I've been struggling with this one all day. I'm making an ajax call to a hard coded JSON file and attempting to store some of the contents into option tags using custom attributes. When I try to retrieve the data that I'm storing in the custom attribute, I keep getting [object Object]. If I try to JSON.stringify() that, I just get "[object Object]" (same as before, except wrapped in double quotes).
Some advice would be very helpful.
This is my currently empty select tag in HTML:
<select id="attackList"></select>
Actual JSON file:
{"attacks":[
{
"attackName":"Jab (1)",
"attackData":{"hitFrame":"9", "faf":"26", "damage":"1.5"}
},
{
"attackName":"Jab (3)",
"attackData":{"hitFrame":"11", "faf":"34", "damage":"2.7"}
},
{
"attackName":"Dash Attack (Early)",
"attackData":{"hitFrame":"15", "faf":"47", "damage":"10"}
},
{
"attackName":"Dash Attack (Late)",
"attackData":{"hitFrame":"21", "faf":"47", "damage":"8"}
},
{
"attackName":"Forward Tilt (1)",
"attackData":{"hitFrame":"12", "faf":"32", "damage":"3.5"}
},
{
"attackName":"Forward Tilt (3)",
"attackData":{"hitFrame":"14", "faf":"43", "damage":"8.5"}
},
{
"attackName":"Up Tilt(1, Early)",
"attackData":{"hitFrame":"7", "faf":"27", "damage":"5"}
},
{
"attackName":"Up Tilt (1, Late)",
"attackData":{"hitFrame":"9", "faf":"27", "damage":"2"}
},
{
"attackName":"Up Tilt (2)",
"attackData":{"hitFrame":"11", "faf":"27", "damage":"6"}
},
{
"attackName":"Down Tilt (Weak)",
"attackData":{"hitFrame":"7", "faf":"26", "damage":"6"}
},
{
"attackName":"Down Tilt (Strong)",
"attackData":{"hitFrame":"7", "faf":"26", "damage":"7"}
},
{
"attackName":"Forward Smash (Weak)",
"attackData":{"hitFrame":"19", "faf":"68", "damage":"14"}
},
{
"attackName":"Forward Smash (Strong)",
"attackData":{"hitFrame":"19", "faf":"68", "damage":"16"}
},
{
"attackName":"Up Smash (Early)",
"attackData":{"hitFrame":"18", "faf":"65", "damage":"17"}
},
{
"attackName":"Up Smash (Mid)",
"attackData":{"hitFrame":"20", "faf":"65", "damage":"16"}
},
{
"attackName":"Up Smash (Late)",
"attackData":{"hitFrame":"22", "faf":"65", "damage":"15"}
},
{
"attackName":"Up Smash (Late)",
"attackData":{"hitFrame":"22", "faf":"65", "damage":"15"}
},
{
"attackName":"Down Smash (1)",
"attackData":{"hitFrame":"20", "faf":"69", "damage":"5"}
},
{
"attackName":"Down Smash (2, Early)",
"attackData":{"hitFrame":"25", "faf":"69", "damage":"16"}
},
{
"attackName":"Down Smash (2, Late)",
"attackData":{"hitFrame":"26", "faf":"69", "damage":"15"}
}
]}
AJAX call that populates the select tag:
$.ajax({
url: attackerFileName,
dataType: 'json',
type: 'get',
cache:true,
success: function(data){
$(data.attacks).each(function(index,value){
console.log(value.attackData);
dropdownOptions.append($("<option></option>").attr("data-value", value.attackData).text(value.attackName));
});
}
});
And the JS code that attempts to retrieve the custom attribute from the currently selected option:
var selectedAttack = $("#attackList option:selected").data("value");
console.log(selectedAttack);
Anyone have any clue why I can't get the actual "attackData" contents from the JSON to come back? If I add code to log the attackData element from the JSON BEFORE its stored into the custom attribute, it comes back just fine. But after I retrieve it, [object Object] is all I get.
Thanks so much in advance to anyone who takes the time to look into this!
The html options can only take primitive values as a string representation.
When you set an option using the attr function, the string representation of the value is taken. In case it is an object, you will get back [object Object] as you are actually storing this value.
However, you can use the $.data function to set the data as an object.
Setting the data value in the following way should do the trick
$('<option></option>').data('value', value.attackData);
or as shown in the code snippet below
'use strict';
var mock = [{
name: 'Option 1',
value: {
identifier: 'option1',
value: {
hello: 'world'
}
}
}, {
name: 'Option 2',
value: {
identifier: 'option2',
value: {
world: 'hello'
}
}
}, {
name: 'Option 3',
value: {
identifier: 'option3',
value: {
sentence: 'hello world'
}
}
}];
$(function() {
setTimeout(function(data) {
// fake postback
var targetElement = $('#dropdown');
data.forEach(function(item) {
var option = $('<option></option>').data('value', item.value).text( item.name );
$(targetElement).append( option );
});
}.bind(null, mock));
$('#dropdown').on('change', function() {
var si = this.selectedIndex,
option = this.options[si],
name = option.text,
value = $.data( option, 'value' );
$('#output').html(name + '<br/>' + JSON.stringify(value));
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="dropdown">
</select>
<div id="output">
</div>

Getting Object Properties From External js File

I'm using a jquery script called jTable (www.jtable.org) to implement dynamic tables in my web application. In order to include a table on a particular page, you must include the following code to declare its properties:
<script type="text/javascript">
$(document).ready(function () {
$('#MyTableContainer').jtable({
//General options comes here
actions: {
//Action definitions comes here
},
fields: {
//Field definitions comes here
}
});
});
</script>
An example of what might go into the fields property:
fields: {
StudentId: {
key: true,
create: false,
edit: false,
list: false
},
Name: {
title: 'Name',
width: '23%'
},
EmailAddress: {
title: 'Email address',
list: false
},
Password: {
title: 'User Password',
type: 'password',
list: false
},
Gender: {
title: 'Gender',
width: '13%',
options: { 'M': 'Male', 'F': 'Female' }
},
BirthDate: {
title: 'Birth date',
width: '15%',
type: 'date',
displayFormat: 'yy-mm-dd'
}
}
The problem is I use the same table (or very similar tables) throughout my web application. I would like to be able to implement a way to store the fields in an external .js file and then refer to it on each page, thus avoiding copying and pasting. On some pages, I may only include some of the above fields (ex. I may want to exclude Password and EmailAddress) or make slight variations to the fields when I load them (ie. use a different displayFormat (for BirthDate) than the default in the external .js file on a particular page.
Thanks!
You can do this in several ways. Here's a simple one:
main.js
//should be modularized/namespaced
var defaultStudentTableFieldsCfg = {
...
};
other-file.js
$(function () {
var tableFieldsCfg = $.extend({}, defaultStudentTableFieldsCfg);
//define new column
tableFieldsCfg.someNewCol = {
//...
};
//remove some column
delete tableFieldsCfg.Password;
//override config
tableFieldsCfg.Gender.title = 'GENDER';
//it would be better not to hard-code #MyTableContainer here
$('#MyTableContainer').jtable({ fields: tableFieldsCfg });
});
You could create functions that you put in external JS files. Then those functions could return the JSON objects needed to construct your jTable.
The problem is the fact that you have a JSON object and that can not be just referenced in a JavaScript file. If you want to load the file, you would need to use something like getJSON and than use that with jQuery.
function createTable(fields) {
$('#MyTableContainer').jtable({
//General options comes here
actions: {
//Action definitions comes here
},
fields: fields
});
}
$(function(){
$.getJSON("YourFields.json", createTable);
});
Now what you are trying to do is reference a global variable.
Place the file before and reference the global variable.
<script type="text/javascript" src="YourFields.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$('#MyTableContainer').jtable({
actions: {
},
fields: fields
});
});
</script>
The YourFields.js file should look more like
if (!window.appDefaults) {
window.appDefaults = {}
}
window.appDefaults.fields = {
StudentId: {
key: true,
...
};

cant get jquery autocomplete to read in js file of data

Using JQuery UI widget to try and call in this js file of string data but getting 'no results found'. No console errors. I simply don't think I'm referencing this correctly as I'm not very proficient with jquery/js. If someone could point me in a direction, I'd appreciate it.
<input type="text" id="test" />
scripts
<script src='js/jquery-1.11.0.min.js'></script>
<script src="js/autocomplete/jquery-ui-1.10.3.custom.js" type="text/javascript" charset="utf-8"></script>
<script src="js/Providers.js" type="text/javascript" charset="utf-8"></script>
formatted in file
var providerdata=[{"ProviderID":"1","NAME":"name1"},{"ProviderID":"2","NAME":"name2"},{"ProviderID":"3","NAME":"name3"}];
calling
$('#test').autocomplete({
source: providerdata,
success: function(data) {
var cat_data = $.map(data.Providers, function(item) {
return {
value: item.NAME,
label: item.NAME,
};
});
$("#test").autocomplete({
minlength:3,
delay: 500,
source: cat_data
});
}
});
uhm... i'm not sure, but i don't think that autocomplete has success property because its a property of an ajax call... maybe you use it inside an ajax call to get back the source, but in your case you already has surce providerdata, true?
Assuming that your $.map works fine, you can do something like:
var cat_data = $.map(providerdata, function(item) {
return {
value: item.NAME,
label: item.NAME,
}
});
$('#test').autocomplete({
source: cat_data,
minlength:3,
delay: 500,
});
[edit] - i see doc and i think you can do also:
$('#test').autocomplete({
source: function(){
return $.map(providerdata, function(item) {
return {
value: item.NAME,
label: item.NAME,
};
})
},
minlength:3,
delay: 500,
});
is it works?

FuelUX datagrid not loading (using example)

I'm new to FuelUX so I was trying to get this to work, based on the example provided:
require(['jquery','data.js', 'datasource.js', 'fuelux/all'], function ($, sampleData, StaticDataSource) {
var dataSource = new StaticDataSource({
columns: [{property:"memberid",label:"LidId",sortable:true},{property:"name",label:"Naam",sortable:true},{property:"age",label:"Leeftijd",sortable:true}],
data: sampleData.memberdata,
delay: 250
});
$('#MyGrid').datagrid({
dataSource: dataSource,
stretchHeight: true
});
});
});
With this as the data:
(function (root, factory) {
if (typeof define === 'function' && define.amd) {
define(factory);
} else {
root.sampleData = factory();
}
}(this, function () {
return {
"memberdata": [{
"memberid": 103,
"name": "Laurens Natzijl",
"age": "25"
}, {
"memberid": 104,
"name": "Sandra Snoek",
"age": "25"
}, {
"memberid": 105,
"name": "Jacob Kort",
"age": "25"
}, {
"memberid": 106,
"name": "Erik Blokker",
"age": "25"
}, {
"memberid": 107,
"name": "Jacco Ruigewaard",
"age":"25"
},{ /* etc */ }]
}
}));
I've got no console errors, no missing includes. Everthing works just fine - it even looks like it's loading. Except nothing shows up in the datagrid but '0 items'.
Any suggestions? I think I did everything the example provided...
EDIT: 14:33 (Amsterdam)
There seems to be a difference when I put this in console:
My page:
require(['jquery','data.js','datasource.js', 'fuelux/all'], function ($, sampleData, StaticDataSource) {
var dataSource = new StaticDataSource({
columns: [{property:"memberid",label:"LidId",sortable:true},{property:"name",label:"Naam",sortable:true},{property:"age",label:"Leeftijd",sortable:true}],
data: sampleData.memberdata,
delay: 250
});
console.debug(dataSource);
});
1st row in console:
function localRequire(deps, callback, errback) { /* etc */ }
2nd row in console:
StaticDataSource {_formatter: undefined, _columns: Array[3], _delay: 250, _data: Array[25], columns: function…}
FuelUX Example:
require(['jquery', 'sample/data', 'sample/datasource', 'sample/datasourceTree', 'fuelux/all'], function ($, sampleData, StaticDataSource, DataSourceTree) {
var dataSource = new StaticDataSource({
columns: [{property: 'toponymName',label: 'Name',sortable: true}, {property: 'countrycode',label: 'Country',sortable: true}, {property: 'population',label: 'Population',sortable: true}, {property: 'fcodeName',label: 'Type',sortable: true}],
data: sampleData.geonames,
delay: 250
});
console.debug(dataSource);
});
1st row in console:
StaticDataSource {_formatter: undefined, _columns: Array[4], _delay: 250, _data: Array[146], columns: function…}
2nd row in console:
function (deps, callback, errback, relMap) { /* etc */ }
Maybe this will help you help me :)
I didn't see all of the information I needed to provide a finite answer. The real magic is the datasource.js file (which you had not provided).
I thought an easier way of demonstrating all the necessary pieces would be to put together a JSFiddle showing your data in use and all the pieces that were necessary.
Link to JSFiddle of Fuel UX Datagrid sample with your data
Adam Alexander, the author of the tool, also has written a valuable example of using the dataGrid DailyJS Fuel UX DataGrid
// DataSource Constructor
var StaticDataSource = function( options ) {
this._columns = options.columns;
this._formatter = options.formatter;
this._data = options.data;
this._delay = options.delay;
};
StaticDataSource.prototype = {
columns: function() {
return this._columns
},
data: function( options, callback ) {
var self = this;
var data = $.extend(true, [], self._data);
// SEARCHING
if (options.search) {
data = _.filter(data, function (item) {
for (var prop in item) {
if (!item.hasOwnProperty(prop)) continue;
if (~item[prop].toString().toLowerCase().indexOf(options.search.toLowerCase())) return true;
}
return false;
});
}
var count = data.length;
// SORTING
if (options.sortProperty) {
data = _.sortBy(data, options.sortProperty);
if (options.sortDirection === 'desc') data.reverse();
}
// PAGING
var startIndex = options.pageIndex * options.pageSize;
var endIndex = startIndex + options.pageSize;
var end = (endIndex > count) ? count : endIndex;
var pages = Math.ceil(count / options.pageSize);
var page = options.pageIndex + 1;
var start = startIndex + 1;
data = data.slice(startIndex, endIndex);
if (self._formatter) self._formatter(data);
callback({ data: data, start: 0, end: 0, count: 0, pages: 0, page: 0 });
}
};
If you were to provide your markup and what your "datasource.js" file contains, I may be able to help you further.
I think the demonstration provides much information on any pieces you may not have understood.
Adding on to creatovisguru's answer:
In his JSFiddle example, pagination is broken. To fix it, change the following line:
callback({ data: data, start: start, end: end, count: count, pages: pages, page: page });
I had the exact same issue, when tried to integrate with Django. The issue I believe is on this line :
require(['jquery','data.js','datasource.js', 'fuelux/all'], function ($, sampleData, StaticDataSource) {
I was not able to specify file extension, my IDE (pycharm), would mark "red", when used "data.js", so it needs to stay without an extension, such as "sample/data"
What I end up doing to make it work, is downloading the full fuelux directory from github in /var/www/html on a plain Apache setup ( no django, to avoid URL.py issues for static files ) and everything works using their example. Here are the steps to get you started :
cd /var/www/html
git clone https://github.com/ExactTarget/fuelux.git
and you will end up with fuelux in /var/www/html/fuelux/
in your browser, navigate to : http://foo.com/fuelux/index.html ( assuming your default document root is /var/www/html )
good luck!

Categories