So, when I view my page source, the json response (aka the table i'm retrieving) is showed instead of the html page.
I've been trying to figure out at first how to retrieve a json response while still rendering the HTML, which had me to come up with this controller code. Would like to help on how to improve my code to solve this problem. Would appreciate suggestions!
My controller:
$products = Product::all();
if (\Illuminate\Support\Facades\Request::ajax())
return response()->json($products);
else
return view('products.index');
Jquery Script:
$(document).ready( function () {
var pathname = window.location.pathname;
loadProducts();
function loadProducts(){
var columns = [{
"sTitle": "Name",
"mData": "name"
}, {
"sTitle": "Price",
"mData": "price"
}, {
"sTitle": "Category_ID",
"mData": "category_id"
}, {
"sTitle": "Supplier_ID",
"mData": "supplier_id"
}]
$.ajax({
'url': '{{ url('products') }}',
'method': "GET",
'contentType': 'application/json'
}).done( function(data) {
var example_table = $('#myTable').DataTable({
"aaData": data,
"columns": columns
});
});
}
I suggest you use DataTable JSONP data source for remote domains
$(document).ready(function() {
$('#example').DataTable( {
"processing": true,
"serverSide": true,
"ajax": {
"url": "scripts/jsonp.php",
"dataType": "jsonp"
}
} );
} );
Related
I have a set of JSON data that are displayed using datatables. In one of the columns, I add a button and a text box only if the value in that column and another column meets a certain condition. this is the bit of code I used to do this:
$(document).ready(function (){
var alertTable = $('#alert-table').DataTable({
"jQueryUI": true,
"order": [ 3, 'desc' ],
"columns": [
{ "data": "source", "visible": false },
{ "data": "host" },
{ "data": "priority" },
{ "data": "ack", "render": function( data, type, row ) {
if (row.ack == "0" && row.priority > "2") {
return '<form><input class="ackname" type="text" value="Enter your name"><input class="ackbutton" type="button" value="Ack Alert" onclick="<get all items for that row and POST to a URL>"></form>';
}
return data;
}
},
],
"language": {
"emptyTable": "No Alerts Available in Table"
}
});
});
This works fine by adding a button and text in the cell. What I am looking to achieve is, when any of the button is been clicked, it should POST all the values for that row including what is typed in the text box to a URL which has another function that would extract those details and update the database and send back the refreshed data. I am new to datatables and jquery, any guide would be highly appreciated.
Have made some changes to the code, instead of form you can use div.
$(document).ready(function (){
var alertTable = $('#alert-table').DataTable({
"jQueryUI": true,
"order": [ 3, 'desc' ],
"columns": [
{ "data": "source", "visible": false },
{ "data": "host" },
{ "data": "priority" },
{ "data": "ack", "render": function( data, type, row ) {
if (row.ack == "0" && row.priority > "2") {
return '<div><input class="ackname" type="text" value="Enter your name"><input class="ackbutton" type="button" value="Ack Alert"></div>';
}
return data;
}
},
],
"language": {
"emptyTable": "No Alerts Available in Table"
}
});
$(document).on("click",".ackbutton",function() {
var currentIndex = $(this).parent().parent().index();
var rowData = alertTable.row( index ).data();
//extract the textbox value
var TextboxValue = $(this).siblings(".ackname").val();
var objToSave = {}; //Create the object as per the requirement
//Add the textbox value also to same object and send to server
objToSave["TextValue"] = TextboxValue;
$.ajax({
url: "url to another page"
data: JSON.stringify({dataForSave : objToSave}),
type: "POST",dataType: "json",
contentType: "application/json; charset=utf-8",
success: function(datas) {
//Your success Code
},
error: function(error) {
alert(error.responseText);
}
});
});
});
Since both the pages are in same project, you can also do it using single ajax, passing all the values to server at once and then calling the other page internally from server and passing in the values using query string.
This is not a running code, rather to give you a basic idea on how to proceed.
Hope this helps :)
I am new to Datatables and trying to figure out this problem.
I have a server which oupts json in certain format(see below).I cant change that on server side.
**Note: I am using link http://www.json-generator.com/j/cftupHnpbC?indent=4 to emulate my server response just for checking.
I have 2 problems
Since My json response doesn't have aaData: thing required by dataTable, I cant seem to initiliaze it.
Even if I add aaData: by hand to json just for checking, dataTable cant count total records.How I can set that manually ?Since I cant change output from server.
JSBIN LINK:
http://live.datatables.net/dasuyaf/1/edit
HTML:
<table id="example" class="display" width="100%">
<thead>
<tr>
<th> </th>
<th>ID</th>
<th>Name</th>
<th>Text</th>
</tr>
</thead>
<tbody></tbody>
</table>
JS:
$(document).ready( function () {
var table = $('#example').dataTable({
"sAjaxSource": "http://www.json-generator.com/j/cftupHnpbC?indent=4",
"aoColumns": [{
"mData": "id",
"mRender": function (data, type, full) {
return '<input type="checkbox" name="chkids[]" value="' + data + '">';
}
}, {
"mData": "id"
}, {
"mData": "name"
}, {
"mData": "text"
}],
"bProcessing": true,
"bServerSide": true,
"sServerMethod": "GET",
"aoColumnDefs": [{
'bSortable': false,
'aTargets': [0]
}],
"fnDrawCallback": function (oSettings) {
console.log(this.fnSettings().fnRecordsTotal());
}
});
});
My Server Output: (cant change this)
[
{
"text": "Some text",
"name": "somedata",
"id": "89"
},
{
"text": "Some text",
"name": "somedata",
"id": "2"
},
{
"text": "Some text",
"name": "somedata",
"id": "12"
}
]
I suppose you could just request that JSON yourself, make an object out of it and pass it to your dataTable.
var aaData;
var table;
$(document).ready( function () {
$.ajax({
url: 'http://www.json-generator.com/j/cftupHnpbC?indent=4'
}).done(function(data){
aaData = data;
table = $('#example').dataTable({
"aaData": aaData,
"aoColumns": [{
"mData": "id",
"mRender": function (data, type, full) {
return '<input type="checkbox" name="chkids[]" value="' + data + '">';
}
}, {
"mData": "id"
}, {
"mData": "name"
}, {
"mData": "text"
}],
"bProcessing": true,
"aoColumnDefs": [{
'bSortable': false,
'aTargets': [0]
}],
"fnDrawCallback": function (oSettings) {
console.log(this.fnSettings().fnRecordsTotal());
}
});
});
} );
I removed bServerSide - I don't think there's any way you can make use of it if you can't change your server response. Also removed sServerMethod.
i am newbie in web programming and datatables and i am trying to add new data to my tables using fnAddData() but it not work
here is my code
$('#btn_ubahbj').click( function() {
//inisialisasi table upproses
Otableupproses=$('#tableupproses').dataTable( {
'sDom': 't',
"bServerSide": false,
"sServerMethod": "POST",
"fnServerParams": function ( aoData ) {
aoData.push( { "name": "idbom", "value": window.id_bom } );
},
"sAjaxSource": "<?=base_url()?>index.php/master_bj/ambilbomproses",
"sAjaxDataProp": "callback",
"bDestroy": true,
"bAutoWidth": false,
"aoColumns": [
{ "sTitle": "ID Proses", "mDataProp": "id_proses_produksi"},
{ "sTitle": "Nama Proses", "mDataProp": "nama"},
{ "sTitle": "Lama Proses", "mDataProp": "waktu"},
{ "sTitle": "Jumlah Mesin", "mDataProp": "jumlah_mesin"},
]
} );
} );
$('#btnuptambahproses').click(
Otableupproses.fnAddData( [$('#prosesupbj').val(),$("#prosesupbj option:selected").text(),$('#txtuplamaproses').val(),$('#txtupjmlmesin').val()]
);
});
my controller name master_bj
function ambilbomproses()
{
$idbom= $this->input->post('idbom');
$res['dataproses']=$this->bom_punya_proses_model->getbomproses($idbom);
echo json_encode(array("callback" => $res['dataproses']));
}
how can i dinamically add new row ?
i use fnAddData() it not work because i get data from json
please help
my model class name bom_punya_proses_model
function getbomproses($idbom)
{
$sql= "SELECT proses_produksi_punya_bom.id_proses_produksi, proses_produksi.nama, proses_produksi_punya_bom.waktu, proses_produksi_punya_bom.jumlah_mesin
FROM proses_produksi_punya_bom
INNER JOIN proses_produksi ON proses_produksi_punya_bom.id_proses_produksi = proses_produksi.id_proses_produksi
WHERE proses_produksi_punya_bom.id_bom = '".$idbom."'";
$result= $this->db->query($sql);
if($result->num_rows() > 0){
return $result->result_array();
}else
return false;
}
no problem with my query and controller , because the json has been performed correctly , but the problem is when i try to add new row data to table ,
Your model does not appear to be using the active records portion of the codeigniter framework at all.
Check the tutorial on the CI website and have a look at the active record help page at :
http://ellislab.com/codeigniter/user-guide/database/active_record.html
I am trying to quickly create a simple display of results from an internal API using DataTables. The API returns JSON in the following structure:
obj {
status: 1,
results: 100,
offset: 25,
limit: 25,
data: [
[1]: {
title: "Blah blah one",
description: "Doesn't really matter",
misc: "Yadda yadda"
},
[2]: {
title: "Blah blah two",
description: "Doesn't really matter",
misc: "Yadda yadda"
},
]
}
I can't/don't want to change the API structure just because DataTables uses a weird structure, but I would like to access the built in functionalities for paging, dynamic loading, etc. DataTables seems to allow for custom data objects, and I've gotten the table to load with the following:
$(document).ready(function() {
$('#example').dataTable( {
"bProcessing": true,
"bServerSide": true,
"sAjaxSource": "http://api.oursite.com/api?limit=100",
"fnServerData": function( sUrl, aoData, fnCallback, oSettings ) {
oSettings.jqXHR = $.ajax( {
"url": sUrl,
"data": aoData,
"success": fnCallback,
"dataType": "jsonp",
"cache": false
} );
},
"sAjaxDataProp": "data",
"aoColumns": [
{ "mData": "title" },
{ "mData": "description" },
{ "mData": "misc" },
]
} );
});
But, none of the paging or sorting functions work. I think this is because DataTables requires a results count and paging variable in the object— "iTotalRecords" and "iTotalDisplayRecords". Is this correct? Is there any way to use the api variables instead? Thanks in advance. I'm currently not getting any errors in the dev console, so if it's erroring it's doing so silently...
While initializing the datatable, instead of directly assigning source to Ajaxsource, you can set the aaData to the javascript function where you can manipulate to return only obj.data. You need handle few things manually.
$('#tblExample').dataTable({
"bJqueryUI": true,
"bDestroy":true,
"bSortable": false,
"sAjaxSource": "",
"aaData":GetData(),
"aoColumns": [
{
"sTitle":"Index","mDataProp": null, "sWidth": "20px", "sDefaultContent": "<span class='ui-icon ui-icon-circle-close' onclick='RemoveActiveItem(this);'></span>", "bSortable": false},
{ "mDataProp": "Year"},
{ "mDataProp": "Month"},
{ "mDataProp": "Savings"}
]
});
I have a Java Web Project where I have a GET endpoint that I am hitting to retrieve JSON data. Firebug shows I am getting the JSON data in the form
[{"id":7,"serial":"7bc530","randomDouble":0.0,"randomDouble2":0.0,"randomDouble3":0.0,"date":1352228474000,"removed":null},
{"id":8,"serial":"4a18d27","randomDouble":0.0,"randomDouble2":0.0,"randomDouble3":0.0,"date":1352228474000,"removed":null},
{"id":9,"serial":"f30ef","randomDouble":0.0,"randomDouble2":0.0,"randomDouble3":0.0,"date":1352228474000,"removed":null},
{"id":10,"serial":"9e6d","randomDouble":0.0,"randomDouble2":0.0,"randomDouble3":0.0,"date":1352228474000,"removed":null},
{"id":11,"serial":"4d8665a3","randomDouble":0.0,"randomDouble2":0.0,"randomDouble3":0.0,"date":1352228474000,"removed":null},
{"id":12,"serial":"4fe1457","randomDouble":0.0,"randomDouble2":0.0,"randomDouble3":0.0,"date":1352228474000,"removed":null}]
On the HTML side I have this,
<table id="table_id">
<thead>
<tr>
<th>id</th>
<th>serial</th>
<th>randomDouble</th>
<th>randomDouble2</th>
<th>randomDouble3</th>
<th>date</th>
<th>removed</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
Here is what I have on the javascript side, I found another post from someone on here with this format that worked for them.
$(document).ready(function() {
var Table = $("#table_id").dataTable({
"bFilter":false,
"bPaginate":false,
"bProcessing": true,
"bServerSide":true,
"bInfo":false,
"sAjaxSource": ApiUrl(),
"fnServerData": function (sSource, aoData, fnCallback){
$.ajax({
"dataType": 'json',
"type": "GET",
"url": sSource,
"data": aoData,
"success": fnCallback
});
}
});
The table is displaying the columns, but it isn't pulling in the data. As I said, I did verify that the JSON data is getting sent to the webpage through Firebug -- through the GET request this is making.
I find datatables to be extremely confusing and I can't get this JSON to actually populate...
Any assistance would be very appreciated.
Edit:
I tried this,
var Table = $("#table_id").dataTable({
"bFilter":false,
"bPaginate":false,
"bProcessing": true,
"bServerSide":true,
"bInfo":false,
"sAjaxSource": ApiUrl(),
"sAjaxDataProp": ""
});
This should work for server side:
var Table = $("#table_id").dataTable({
"bFilter":false,
"bPaginate":false,
"bProcessing": true,
"bServerSide":true,
"bInfo":false,
"aoColumns": [
{ "mData": "id" },
{ "mData": "serial" },
{ "mData": "randomDouble" },
{ "mData": "randomDouble2" },
{ "mData": "randomDouble3" },
{ "mData": "date" },
{ "mData": "removed" }
],
"sAjaxSource": "url",
"fnServerData": function ( sSource, aoData, fnCallback ) {
$.getJSON( sSource, aoData, function (json) {
map = {}
map["aaData"] = json
fnCallback(map)
} );
}
});
UPDATE regarding last comment:
"fnServerData": function ( sSource, aoData, fnCallback ) {
$.getJSON( sSource, aoData, function (json) {
$.getJSON('second_json_url', function(secondjson) {
$.each(secondjson, function(index, object) {
json[index].serial = secondjson[index].name
})
map = {}
map["aaData"] = json
fnCallback(map)
})
});
}
You can read from an arbitrary data source. Check out the documentation below (found here). This works for server-side processing and ajax data sources.
Additionally, it is possible to set sAjaxDataProp to be an empty
string, which results in DataTables treating the given data source as
the table data array (rather than as property of an object).