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!
Related
I am a beginner in TYPO3 and have to say its very complex but I am struggling my way through.
I just want a simple way to get content from an internal TYPO3 Database Table which I created and forward it to JavaScript/JQuery/AJAX.
My BootstrapTable is working but just displays static content from var data.
I know there are ways from pageType, eID and $GLOBALS['TYPO3_DB']->exec_SELECTgetRows( /* ... */ ); to get the content of the Database Table, but how to forward it to JavaScript and display it?
There should not be another database call with credentials, just a way to the internal Database.
Searching for this answer since 2 days but can't find any easy and plausible answer.
Or do I have to take the long road via eID or pageType?
Edit due to comment:
Here is my JavaScript with bootstrapTable:
$(function () {
$('#table').bootstrapTable({
idField: 'name',
pagination: true,
search: true,
data: data,
columns: [{
field: 'name',
title: 'Name'
}, {
field: 'stargazers_count',
title: 'Stars'
}, {
field: 'forks_count',
title: 'Forks'
}, {
field: 'description',
title: 'Description'
}],
onPostBody: function () {
$('#table').editableTableWidget({editor: $('<textarea>')});
}
});
});
var data = [{
"name": "bootstrap-table",
"stargazers_count": "526",
"forks_count": "122",
"description": "An extended Bootstrap table with radio, checkbox, sort, pagination, and other added features. (supports twitter bootstrap v2 and v3) "
}, {
"name": "multiple-select",
"stargazers_count": "288",
"forks_count": "150",
"description": "A jQuery plugin to select multiple elements with checkboxes :)"
}, {
"name": "bootstrap-show-password",
"stargazers_count": "32",
"forks_count": "11",
"description": "Show/hide password plugin for twitter bootstrap."
}, {
"name": "blog",
"stargazers_count": "13",
"forks_count": "4",
"description": "my blog"
}, {
"name": "scutech-redmine",
"stargazers_count": "6",
"forks_count": "3",
"description": "Redmine notification tools for chrome extension."
}
];
And calling it in my html with : <table id="table"></table>
My own created table in mysql database is: tx_table
I want the content of that table to be displayed in my bootstraptable Table
First solution. You can output your results directly into html using <script> tag and v:format.json.encode ViewHelper
action code:
$yourDataArrayFromPHP = array(
'var1' => 'val1',
'var2' => 'val2'
);
$this->view->assign('yourDataArrayFromPHP', $yourDataArrayFromPHP);
html:
<script>
var data = {v:format.json.encode(value: '{yourDataArrayFromPHP}')}
</script>
Now you can access this data in javascript data.var1
Also keep in mind that your data should be before bootstrapTable initialization.
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
});
I am new to angular and trying to develop an application having nested
ng-repeat and after submitting the form it should hit the rest api.
I have been using $http to make rest api calls. The code gets submitted
with normal data but does not get submitted with nested ng-repeat when i
click the save button. Below I have provided the code with details.
The whole data should be shown in the console. I might have made some
mistake somewhere.Thanks in advance.
JS
$scope.saveVenFormData = function(vendet){
console.log($scope.vendet);
$scope.venFullAddress.push({
'vendorName': $scope.name,
'panNum': $scope.panNum,
'personName': $scope.venBusDetails.personName,
'mobileNum': $scope.venBusDetails.mobileNum,
'workNum': $scope.workNum,
'emailid': $scope.emailid,
'addressLine1': $scope.addressLine1,
'addressLine2': $scope.addressLine2,
'city': $scope.city,
'state': $scope.state
});
var dataObj = $scope.venFullAddress;
// console.log($scope.dataObj);
$http.get('/showVendors').success(function(data){
console.log(angular.toJson(data));
});
var res = $http.post('http://localhost:8080/dman/mm', dataObj);
res.success(function(data, status, headers, config) {
$scope.message = data;
});
res.error(function(data, status, headers, config) {
alert( "failure message: " + JSON.stringify({data: data}));
});
};
JSON structure:
{
"vendor": {
"vendorName": "",
"panNum": "",
"venBusDetails": [{
"personName": "",
"mobileNum": "",
"workNum": "",
"emailid": "",
"venContDetails": [{
"addressLine1": "",
"addressLine2": "",
"city": "",
"state": ""
}]
}]
}
}
https://plnkr.co/edit/nP8R92KNkz8JEHpvH56S?p=catalogue
For convenience I have added a json structure. I need to access all the
data from the form and hit the rest api.
The above is the link to the plunker. Thank you.
Try this
$scope.dataObjToPost = {
"vendor": {
"vendorName": $scope.vendet.vendorName,
"panNum": $scope.vendet.panNum,
"venBusDetails": [{
"personName": $scope.venBusDetails[0].personName,
"mobileNum": $scope.venBusDetails[0].mobileNum,
"workNum": $scope.venBusDetails[0].workNum,
"emailid": $scope.venBusDetails[0].emailid,
"venContDetails": [{
"addressLine1": $scope.venContDetails[0].addressLine1,
"addressLine2": $scope.venContDetails[0].addressLine2,
"city": $scope.venContDetails[0].city,
"state": $scope.venContDetails[0].state
}]
}]
}
} //And send this data to POST method
You used $scope.name in JS file but in HTML view you used ng-model="vendet.vendorName". Thats why it is always undefined.
UPDATED ANSWER Plunk LINK IS HERE
Apologies in advance - I am new to this and so other answers have not been able to help me.
I have used AJAX to send data to a PHP script (part of a 3rd party API). The PHP script returns the results as JSON, but I have no idea how to format these on my HTML page.
Ultimately, I would like to save the JSON results as an array and then use JS/Jquery to format them on the page.
I am not sure how to modify the PHP and AJAX scripts to achieve this. Can anyone point me in the right direction?
My AJAX:
$.ajax({
type: 'POST',
url: 'calculator.php',
data: {toPostcode: toPostcodeValue, parcelLengthInCMs: parcelLengthInCMsValue, parcelHeighthInCMs: parcelHeighthInCMsValue, parcelWidthInCMs: parcelWidthInCMsValue, parcelWeightInKGs: parcelWeightInKGsValue},
success: function(data) {
<!--NOT SURE WHAT TO PUT HERE-->
}
})
PHP (after the calculator does its thing - not sure if it needs to be changed):
$serviceTypesJSON = json_decode($rawBody);
echo json_encode($serviceTypesJSON);
The expected JSON results should look like:
{
"services": {
"service" : [
{
"code": "AUS_PARCEL_REGULAR",
"name": "Parcel Post (your own packaging)",
"speed": 2,
"price": 6.95,
"max_extra_cover": 5000,
"extra_cover_rule": "100,1.5,1.5",
"icon_url": "http://test-static.npe.auspost.com.au/api/images/pac/regular_post_box.png",
"description": "Based on the size and weight you've entered",
"details": "Check our ",
"delivery_time": "Delivered in up to 3 business days",
"ui_display_order": 1,
"options": {
"option": [
{
"code": "AUS_SERVICE_OPTION_STANDARD",
"name": "Standard Service",
"price": "0.00",
"price_type": "static",
"option_type": "optional",
"ui_display_order": 1
},
{
"code": "AUS_SERVICE_OPTION_SIGNATURE_ON_DELIVERY",
"name": "Signature on Delivery",
"price": 2.95,
"price_type": "static",
"option_type": "optional",
"tooltip": "Signature on Delivery provides you with the peace of mind that your item has been delivered and signed for.",
"ui_display_order": 2,
"suboptions": {
"option": {
"code": "AUS_SERVICE_OPTION_EXTRA_COVER",
"name": "Extra Cover",
"option_type": "optional",
"price_type": "dynamic",
"tooltip": "Extra Cover provides cover for loss, damage or theft of your item and will fully compensate you to the value specified for your item.",
"ui_display_order": 1
}
}
}
]
}
},
You can do two things, if the return data is JSON use dataType: "json" in the AJAX call.
Edit 1
If you are using dataType: "json". Which is more preferred if you are sure the data return is JSON string. data variable in the success will directly give you the JSON object. I think you can access it like data['services'].
success: function (data) {
jsonObj = $.parseJSON(data);
//this gives you the inner onject of the return data
servicesObj = jsonObj.services;
}
Or you can just get the data then use jQuery.parseJSON() to parse the data string into JSON object.
$.ajax({
type: 'POST',
url: 'calculator.php',
data: {
toPostcode: toPostcodeValue,
parcelLengthInCMs: parcelLengthInCMsValue,
parcelHeighthInCMs: parcelHeighthInCMsValue,
parcelWidthInCMs: parcelWidthInCMsValue,
parcelWeightInKGs: parcelWeightInKGsValue
},
success: function (data) {
jsonObj = $.parseJSON(data);
//this gives you the inner onject of the return data
servicesObj = jsonObj.services; //or jsonObj["services"]
}
})
Your success function will never be called if you are using
echo json_encode(); in your php script.
You should add dataType:'json' after type:'POST' and then your success function will get called and will get the result returned by server in data
I'm a first time user of jqGrid, so far I went trough official examples, I'm interested in loading data into grid either using json.
I'm currently looking at, Loading data(JSON Data):
http://trirand.com/blog/jqgrid/jqgrid.html
Here is a bit of javascript that creates grid :
jQuery("#list2").jqGrid(
{
url : '<c:url value="${webappRoot}/getdetails" />',
datatype : "json",
colNames : [ 'id', 'Location', 'Country Code', 'Type', 'Interval',
'Version', 'Last Active', 'Last Login', 'NOTE' ],
colModel : [
{ name : 'id', width : 10 },
{ name : 'location', width : 75 },
{ name : 'countryCode', width : 50 },
{ name : 'type', width : 40 },
{ name : 'interval', width : 30 },
{ name : 'version', width : 45 },
{ name : 'lastactive', width : 50, align : "right" },
{ name : 'lastlogin', width : 50, sortable : false },
{ name : 'note', width : 50, sortable : false}
],
rowNum : 10,
rowList : [ 10, 20, 30 ],
pager : '#pager2',
width: gridWidth,
sortname : 'id',
viewrecords : true,
sortorder : "desc",
caption : "JSON Example"
});
jQuery("#list2").jqGrid('navGrid', '#pager2',
{ edit : false, add : false, del : false});
${webappRoot}/getdetails transforms path to my project like http://localhost/myProject/getdetails, I'm using spring MVC(it might be irrelevant).
When I look in firebug this generates this http request :
GET http://localhost/newProject/getdetails?_search=false&nd=1304638787511&rows=10&page=1&sidx=id&sord=desc
200 OK
135ms
Here is the response :
{
"id": 1,
"location": "office_2782",
"countryCode": "UK",
"quarter": "500",
"version": "v3.05",
"lastactive": "yesterday",
"lastlogin": "today",
"note": "no note",
"type": "read-only"
}
When I navigate to JSON tab it all seems same as this, any idea what I'm doing wrong?
I'm trying to load only one record for start, and I can't get it working, any help is appriciated.
First of all you are not the first person who has problems understanding how the JSON data should be constructed, what the parameters sent from jqGrid to the server mean and so on. The official jqGrid documentation doesn't contain enough introduction, so the first steps of the jqGrid usage can be a little more difficult than one expect.
The problem which exists in your JSON response from the server is that it contains only one item of data instead of an array (or list) of items representing the grid rows. The data should be at least
[
{
"id": 1,
"location": "office_2782",
"countryCode": "UK",
"quarter": "500",
"version": "v3.05",
"lastactive": "yesterday",
"lastlogin": "today",
"note": "no note",
"type": "read-only"
}
]
or better as
{
"total": 1,
"page": 1,
"records": 1,
"rows": [
{
"id": 1,
"location": "office_2782",
"countryCode": "UK",
"quarter": 500,
"version": "v3.05",
"lastactive": "yesterday",
"lastlogin": "today",
"note": "no note",
"type": "read-only"
}
]
}
or even as
{
"total": 1,
"page": 1,
"records": 1,
"rows": [
{
"id": 1,
"row": [ "1", "office_2782", "UK", "500", "v3.05",
"yesterday", "today", "no note", "read-only" ]
}
]
}
or
{
"total": 1,
"page": 1,
"records": 1,
"rows": [
[ "1", "office_2782", "UK", "500", "v3.05", "yesterday", "today",
"no note", "read-only" ]
]
}
The reason of such strange at the first glance JSON data is that jqGrid is designed to support paging, sorting and filtering/searching of data implemented on the server. So the parameters rows=10&page=1&sidx=id&sord=desc from the url sent to the server mean that jqGrid asks the server to get the first page (page=1) of the data with the page having 10 rows per page (rows=10). The data should be previously sorted by id (sidx=id) in the descending order (sord=desc). If you has small number of rows (under some hundert for example) you can use client based sorting, paging and filtering if you add loadonce:true parameter of the jqGrid, but the server based implementation allows you to work with really large dataset having many hundred thousands rows of data with very good performace.
I recommend you to read my this answer where I tried to explain how the additional elements of the server response "total", "page" and "records" will be used. The values of the parameters can be encoded in JSON either as numbers or as strings (on your taste).
If the user clicks on the column header of the 'location' column for example jqGrid will send new request to the server having sidx=location&sord=asc in the url. So it is important to understand, that the server can be asked to provide the data for the grid not once per grid, but many times and the request will contain some parameters chosen by the user who works with the jqGrid.
Defining of jsonReader (and sometimes additional jsonmap parameters for every column) you describe the structure of the server response. Using the information jqGrid read the response and fill the grid.
The demo shows that with the corresponding jsonReader you can read even your original JSON data.
The last advice for you from me would be to consider at the beginning to use loadError event handle which helps to inform the user about the errors reported by the server. In the answer I have shown how it can be implemented in the case of ASP.NET MVC. I don't use spring MVC myself so I can't give you direct examples of how to better implement the error reporting in spring MVC, but the main idea is the same in any server technology: in case of errors the server should respond with the response having an error HTTP status code. Inside of your implementation of the loadError event handle you decode the response and display the information about the error.