I haven't needed to access JSON data so I'm a bit stumped. I've validated the data using a JSON formatter and it is valid so I know that is good.
All I'm trying to do is retrieve the data and populate a select box (specifically x-editable).
In there example, they provide:
$('#id').editable({
source: [
{value: 1, text: 'Male'},
{value: 2, text: 'Female'}
]
});
Yes, I could throw the 50 states in there but I'd like to use this same approach for other select boxes I plan on implementing.
Here is the datafeed I'm currently getting back from my JSON call:
{
"data": [{
"stateID": 1,
"stateAbbr": "AL",
"state": "Alabama"
}, {
"stateID": 2,
"stateAbbr": "AK",
"state": "Alaska"
}, {
"stateID": 3,
"stateAbbr": "AZ",
"state": "Arizona"
}, {
"stateID": 51,
"stateAbbr": "WY",
"state": "Wyoming"
}]}
My function snippet that I'm working with is:
$.getJSON("test.html?format=json",function(data){
statesArr = statesArr.concat(data);
});
Ideally, I'd like to make the statesArr look like this:
source: [
{value: 1, text: 'Alabama'},
{value: 2, text: 'Alaska'},
...
{value:50, text: 'Wyoming'}
]
But I'm at a loss on what to do from here. The format of the data feed, {"data is throwing me off. I'm used to getting data pretty much like X-Editable is looking for.
I am assuming here that resp is the response. And resp has data property. If I have misunderstood you, please tell me so.
var statesArr;
$.getJSON('test.html?format=json', function(resp){
statesArr = resp.data.map(function(state){
return {
value: state.stateID,
text: state.state
}
});
});
/* somewhere else later; make sure that statesArr is set */
$('#id').editable({
source: statesArr
});
Related
I am working on a project using Laravel and yajrabix/laravel-datatables. I am having an issue when trying to access a column using columndefs. The column is supposed to be JSON data. Nothing is working to work with the data in that column. Is there a way to send the data unmodified for that column?
Bottom line, I would like to be able to access the data from the json stored in the results column. No matter what I do, it doesnt work.
Here is the code in my blade view. Everything else works on the datatable.
<script type="text/javascript">
$(function () {
var table = $('.table').DataTable({
processing: true,
serverSide: false,
ajax: "/admin/logs/datatable/lookup-ip",
columns: [
{data: 'id', name: 'id'},
{data: 'ip_address', name: 'ip_address'},
{data: 'results', name: 'results'},
{data: 'created_by', name: 'created_by'},
{data: 'created_at', name: 'created_at'},
],
columnDefs: [
{
targets: "_all",
className: 'nk-tb-col tb-col-mb'
},
{
targets: 2,
render: function (data, type, row, meta) {
return 'ISP: ' + data.ip;
}
}
],
});
});
</script>
This is the function in the controller serving the datatable.
public function datatable($log)
{
switch($log)
{
case 'activity':
$table = config('activitylog.table_name');
break;
case 'lookup-ip':
$table = IPLookup::getModel()->getTable();
break;
case 'lookup-phone':
$table = PhoneLookup::getModel()->getTable();
break;
}
$query = DB::table($table);
return DataTables::of($query)->toJson();
}
This is the data that is stored in the database.
{"ip": "8.8.8.8", "asn": "AS15169", "isp": "Google LLC", "org": "Google LLC", "city": "Ashburn", "type": "IPv4", "region": "Virginia", "country": "United States", "success": true, "currency": "US Dollar", "latitude": "39.0437567", "timezone": "America/New_York", "continent": "North America", "longitude": "-77.4874416", "country_code": "US", "country_flag": "https://cdn.ipwhois.io/flags/us.svg", "timezone_gmt": "GMT -5:00", "country_phone": "+1", "currency_code": "USD", "timezone_name": "Eastern Standard Time", "continent_code": "NA", "currency_rates": "1", "country_capital": "Washington", "currency_plural": "US dollars", "currency_symbol": "$", "completed_requests": 29, "country_neighbours": "CA,MX,CU", "timezone_dstOffset": "0", "timezone_gmtOffset": "-18000"}
The model of the IP log has casts setup.
protected $casts = [
'results' => 'array',
];
Okay so it figures after posting the question... I figure it out.
According to yajrabox:
By default, Laravel DataTables protects us from XSS attack by escaping all our outputs. In cases where you want to render an html content, please use rawColumns api.
So I modified the code in the controller returning the datatable and now it works as expected and I can parse the JSON and use it as an object in javascript.
return DataTables::of($query)
->rawColumns(['results'])
->toJson();
One thing I've notice is that the data stored on your database, according to your example, isn't wrapped into the array brackets ([ ]) and you're using a cast on the Module. That could be the cause of the problem.
Try going to your database and manually wrapping your JSON on array brackets and give it a shot!
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 :)
I'm trying to get the data with json to generate a footable table with pagination but it's not working.
my code actualy look like this.
sorry my bad english.
my index.json is returning it
{
Cartas: [
{
id: 3,
user_id: 1,
status: "2",
banco_cartas: null,
nome: "teste",
contrato: "",
grupo: "430",
cota: "3332",
credito_atual: 154371.02,
prazo_original: "",
prazo_atual: "126",
valor_parcela: "0",
pc_pago: 1,
pc_fc: 0,
valor_pago: 154371.02,
saldo_devedor: null,
taxa: 0,
data_compra: "2003-03-28T00:00:00+00:00",
created: "2017-06-22T17:39:23-03:00",
data_contemplacao: "2016-12-20T00:00:00+00:00",
data_entrega: null
},
{
id: 4,
user_id: 1,
status: "2",
banco_cartas: null,
nome: "CAS REP comerciais",
contrato: "",
grupo: "240",
cota: "320",
my jquery to load the json in footable
jQuery(function($){
$('#custom-ui-example').footable({
"columns": [
{ name: "nome",
title: "Nome"},
{ name: "credito_atual",
title: "Crédito Atual"},
{ name: "status",
title: "Status"}
],
"rows": $.get("index.json")
})};
my html
<table class="table" id="custom-ui-example" data-paging="true"></table>
Index.json should return array of objects, in your case it is returning object.
The format of the json should be
[{'id': '3'},{'id': '4'}]
Pagination seems to work fine.
Find the working fiddle here: https://jsfiddle.net/qwwjs7j3/
first of all, you should check if your json is valid. you can do that here for example: https://jsonformatter.curiousconcept.com/
then you can should make the get-call using:
$.get({
url: 'index.json'
}).done(function(data) {
data = JSON.parse(data);
});
the return data is hold in the data object of the callback function.
I'm following this link which is a great clear blog post about typeahead.js with Json. However, I'm having problems with it and can't figure out where I'm going wrong.
Here is my js:
<script type="text/javascript">
$('#Search').typeahead({
hint: true,
highlight: true,
minLength: 1
},
{
name: 'states',
displayKey: 'stateName',
source: function (query, process) {
states = [];
map = {};
var data = [
{ "stateCode": "CA", "stateName": "California" },
{ "stateCode": "AZ", "stateName": "Arizona" },
{ "stateCode": "NY", "stateName": "New York" },
{ "stateCode": "NV", "stateName": "Nevada" },
{ "stateCode": "OH", "stateName": "Ohio" }
];
$.each(data, function (i, state) {
map[state.stateName] = state;
states.push(state.stateName);
});
process(states);
},
updater: function (item) {
selectedState = map[item].stateCode;
return item;
}
});
</script>
When I type in the input control all the results come back as undefined. I think it's something to do with the displayKey and I've tried setting it to state.stateName but that results in the same problem. Maybe I'm looking in the wrong area?
I've setup a plnkr.co demo here.
Thanks for reading.
Paul
You need to change your states.push row, in your plunker it is on row 45.
Typeahead expects results in JSON format, now you are just pushing results.
Change row 45 to:
states.push({stateName : state.stateName});
Now your displayKey: "stateName" (which is the key of JSON formatted data) will exist and it will show the name of the state as a result.
I have this json array
[
{
Company:
{
id: "19",
features_id: null,
features: "a:6:{i:1;s:1:"1";i:2;s:1:"2";i:3;s:1:"3";i:4;s:1:"0";i:5;s:1:"0";i:6;s:1:"6";}"
},
User: [ ]
},
-{
Company:
{
id: "20",
features_id: null,
features: "a:6:{i:1;s:1:"1";i:2;s:1:"2";i:3;s:1:"3";i:4;s:1:"4";i:5;s:1:"5";i:6;s:1:"6";}"
},
User:
[
{
id: "1",
group_id: "1",
type: null
}
]
}]
for somereason I cant get data into my div. Anyhelp will be appreciated. here is the jsfidler
http://jsfiddle.net/4Y9L3/
That JSON is not valid. Also, your template is not going to output anything visible unless you put some bind tags in the repeater like {{Company.Company.id}} for example.
You are using $.ajax(), so Angular doesn't know about it.
Use $http like this http://jsfiddle.net/4Y9L3/5/.