I have some sort of
[
{
"selectionId":1,
"selectionDate":"101662",
"selectedBy":"ABC",
"eximPanNo":222,
"eximPanName":"DEF",
"eximPanNameEng":"KKK",
"eximPanAddress":null,
"eximPanAddressEng":null,
"eximPanPhone":12334566,
"selectionType":"G",
"consignmentNo":0,
"consignmentDate":"2098",
"productName":"LLL",
"selectionFromDate":"2019",
"selectionToDate":"2090",
"agentNo":123,
"selectionStatus":"I",
"entryBy":"PCS",
"entryDate":"2018-11-22 11:46:02",
"rStatus":"F",
"custOfficeId":1,
"selectionAudit":[
{
"audGrpId":1,
"selectionId":1,
"assignFromDate":"2075-08-03",
"assignToDate":"2075-08-19",
"entryBy":"1",
"rStatus":"1"
}
]
}
]
How can i show this selectionAudi.audGrpId data in dataTable when called from AJAX?
Here the Api is called through AJAX.
var table = $('#nepal').DataTable({
"processing" : true,
"ajax" : {
"url" : A_PAGE_CONTEXT_PATH + "/form/api/getAllSelectionAudit/all",
dataSrc : ''
},
"columns" : [ {
"data" : "selectionId"
}, {
"data" : "selectionDate"
}, {
"data" : "selectedBy"
}, {
"data" : "eximPanNo"
} ]
});
But when I add "data":"selectionAudi.audGrpId" then the datatable shows error like :
The code for table is:
<table id="nepal" class="table table-bodered">
<thead>
<tr>
<th>Selection No</th>
<th>SelectionDate</th>
<th>SelectedBy</th>
<th>PanEximNumber</th>
<th>AudiGroupID</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
How can i show the inner Json data into datatable?I am not able to see what is the real solution.
Your problem is that selectionAudit is an array with one object that contains the audGrpId property, so writing just selectionAudi.audGrpId is what's throwing this Error, because it's trying to access the audGrpId property in the array.
What you need is to write selectionAudit[0].audGrpId to access the right property.
This is how should be your code:
var table = $('#nepal').DataTable({
"processing" : true,
"ajax" : {
"url" : A_PAGE_CONTEXT_PATH + "/form/api/getAllSelectionAudit/all",
dataSrc : ''
},
"columns" : [ {
"data" : "selectionId"
}, {
"data" : "selectionDate"
}, {
"data" : "selectedBy"
}, {
"data" : "eximPanNo"
}, {
"data" : "selectionAudit[0].audGrpId"
]
});
Note:
This assumes selectionAudit is an array and it's always filled with this object.
You can follow the way I usually do it not server side processing of datatable.
Suppose you HTML page from where you are making API calls -
<!-- Button to make API request -->
<button id="btnAPIRequest">API Request</button>
<!-- API response div -->
<div id="responseAPI"></div>
Call the API request through AJAX GET method and add below javascript code in bottom of your HTML page -
<script>
$("#btnAPIRequest").click(function(){
$.ajax({
type: "GET",
url: "Your/url/to/page.php",
data: 'if you have any data else blank',
dataType: 'json',
success: function(data){
if(data.success){
$("#responseAPI").html(data.message);
// Initialize datatable here
}
else{
$("#responseAPI").html(data.message);
}
}
});
});
</script>
Now in your php page where you actually calls the API and decode the json response -
<?php
// Load the reuiqred library
// Make API request
// Get the resonse in json
$response = '[{"selectionId":1,..."selectionAudit":[{"audGrpId":1,..."rStatus":"1"}]}]';
// Decode the json response
$decoded_data = json_decode($response);
// Get your html table
$msg = '
<table>
<thead>
<tr>
<th>Selection No</th>
<th>SelectionDate</th>
<th>SelectedBy</th>
<th>PanEximNumber</th>
<th>AudiGroupID</th>
</tr>
</thead>
<tbody>
';
// Table body data
foreach($decoded_data as $data){
$msg .= '
<tr>
<td>'.$data[0].'</td>
<td>'.$data[2].'</td>
<td>'.$data[3].'</td>
<td>'.$data[4].'</td>
';
// I think here you got stuck when extracting from multidimensional array
foreach($data[n] as $audi_data){
$msg .= '<td>'.$audi_data[i].'</td>';
}
$msg .= '</tr>';
}
$msg .= '</tbody></table>';
// For success respone
// encode this value in json and ajax response will handle this as per return datatype option
echo json_encode(array('success'=>true, 'message'=>$msg));
// Similarly for failed response
echo json_encode(array('success'=>true, 'message'=>$msg));
?>
Related
I have a datatable and am fetching the data from an api. Now i have the status like active,inactive if the flag is active then i need to show in the datatble else i should not show the expired one.Here is my fiddle. In this fiddle am showing the active and inactive both. but i want to show only the active status.
HTML
<table id="example" class="display" cellspacing="0" width="100%">
<thead>
<tr>
<th>Name</th>
<th>Email</th>
<th>Subject</th>
<th>Status</th>
<th>Message</th>
<th>Details</th>
</tr>
</thead>
</table>
SCRIPT:
$(document).ready(function() {
$('#example').DataTable({
"processing" : true,
"ajax" : {
"url" : "https://api.myjson.com/bins/12uwp2",
dataSrc : ''
},
"columns" : [ {
"data" : "name"
}, {
"data" : "email"
}, {
"data" : "subject"
}, {
"data" : "status"
},{
"data" : "message"
},
{
"mData": "Details",
"mRender": function (data, type, row) {
return "<a class='delete' data-id=" + row.id + " href='/Details/" + row.id + "'>Delete</a>";
}
}]
});
$(document).on("click", ".delete", function(e) {
e.preventDefault()
alert("Delete button clicked for Row number " + $(this).data("id"))
})
});
How to do this. Can anyone help me how to do.
The use case is: Manipulate the data returned from the server
$('#example').DataTable({
"ajax" : {
"url" : "https://api.myjson.com/bins/12uwp2",
"dataSrc": function ( json ) {
return json.filter(function(item){
return item.status=="active";
});
}
}
});
The key is to use dataSrc properly for data manipulation.
As a function - As a function it takes a single parameter, the JSON
returned from the server, which can be manipulated as required. The
returned value from the function is what will be used by DataTables as
the data source for the table.
I recommend to remove the processing property from DataTable initialization object since there is no heavy processing step anymore.
Docs
Load data for the table's content from an Ajax source - Examples
Live Example - JSFiddle
Clean code example using a separate filter function - JSFiddle
I am trying to setup datatables to read my json API to display data in a table. Currently it is outputting all of the object contents into one line instead of looping it like a table should be displayed.
My jsfiddle
HTML
<table id="example" class="display" cellspacing="0" width="100%">
<thead>
<tr>
<th>Blocks</th>
<th>Amount</th>
<th>Date</th>
</tr>
</thead>
</table>
JS
$(document).ready(function() {
$('#example').DataTable({
"processing" : true,
"ajax" : {
"url" : "https://zelcash.voidr.net/api/payments",
dataSrc : ''
},
"columns" : [ {
"data" : "payments.[].blocks.[]"
}, {
"data" : "payments.[].amounts.t1XHpNtYY2N3EMDRoX9RM2hq4DWWPZSmawJ"
}, {
"data" : "payments.[].time"
}]
});
});
You need an endpoint to return only an array, because this endpoint https://zelcash.voidr.net/api/payments return some objects.
You can check the datatables documentation:
https://datatables.net/examples/data_sources/ajax in this example the ajax url is https://datatables.net/examples/ajax/data/arrays.txt and this return an array.
I have a view in which I have a detailview and a gridview. In my grid view there are check-boxes against all the columns. The detail view contains the model id. Now the case is simple, I want to select any column from the grid view and then on click of the a link button I want to send the ajax call, which includes the value of selected column and the model id, to my controller. Below is my view
<?= GridView::widget([
'dataProvider' => $dataProvider,
/*'filterModel' => $searchModel,*/
'columns' => [
['class' => 'yii\grid\CheckboxColumn', 'checkboxOptions' => function($d) {
return ['value' => $d['meter_id']];
}],
'Meter_Serial_Number',
'Issued_To',
'Store',
],
]); ?>
Set PDF
Now the javascript and the ajax call
<?php
$url = Url::toRoute(['/ogpheader/viewsetpdf','id'=>$model->id]);
$script = <<< JS
$(document).ready(function () {
$('#myid').on('click',function() {
var strValue = "";
$('input[name="selection[]"]:checked').each(function() {
if(strValue!="")
{
strValue = strValue + " , " + this.value;
}
else
strValue = this.value;
});
// alert(strValue);
$.ajax({
url: '$url',
type: 'POST',
data: {
data: strValue,// also tired with {strValue:strValue id:id} but it did not worked for me as well
},
success: function(data) {
alert(data);
},
});
})
});
JS;
$this->registerJs($script, static::POS_END);
?>
Action Controller
public function actionViewsetpdf($id)
{
$model = $this->findModel($id);
print_r($_POST);
$data = "";
if(Yii::$app->request->isAjax)
{
$data = json_decode($_POST['data']);
print_r($data);
}
else{
echo 'no data';
}
exit();
}
The response i always got is Array ( ) no data. I have also looked into Passing two parameters in yii2 ajax request using jquery to a controller and Yii2 extra parameter ajax in controller but both seems to be helpful in my case.
Note:
As per my understanding the id is a get and strValue is post. So I am confused in both of them. May be I am wrong.
Update 1
Image quality is not that good
The response in Xhr is
array(1) {
["data"]=>
array(1) {
["data"]=>
string(26) "99 , 100 , 101 , 102 , 103"
}
}
Any help would be highly appreciated.
Prevent the default click event
$('#myid').on('click',function(e) {
e.preventDefault();
I have a jQuery datatable that uses an Ajax data source. The table is defined as follows:
$("#tblNotes").DataTable({
"ajax" : {
"url": "/projects/ajaxGetProjectNotes/",
"type" : "post",
"dataType" : "json",
"data" : {"idProject" : "b92792db-9ea6-49bf-b4dc-1cdf3f441148"}
},
"columns" :
[
{"data" : "dComment", "width" : "130px", "orderable" : true},
{"data" : "cComment", "width" : "270px", "orderable" : false}
]
});
The ajax response from the php script is:
[{"dComment":"","cComment":""}]
I am getting an error:
TypeError: aData is undefined
for ( i=0 ; i<aData.length ; i++ ) {
-------------^
The error is coming from datatables.js (line 15748, col 18).
Here's the source of the ajax source (and the accompanying model function that retrieves the data). Note that this is codeigniter based code (but I don't think that will make much of a difference):
function ajaxGetProjectNotes(){
$id = $_POST["idProject"];
$notes = $this->projects_model->getNotes($id);
if(!isset($notes[0]["cComment"])){
$notes[0]["dComment"]="";
$notes[0]["cComment"]="";
}
echo json_encode($notes);
}
The model code:
function getNotes($idProject){
$this->db->select("*")
->from("projectnotes")
->where("idProject", $idProject);
$query = $this->db->get();
$aResult = $query->result_array();
return $aResult;
}
The error is occuring when the page loads.
Any assistance would be appreciated...
I am using CodeIgniter and DataTables(link) with library IgnitedDatatables(link).
I dont know how to use something like strip_tags() in DataTables. I just need to remove all html tag output from JSON data.
My JavaScript Code :
var table = $('#dtslider').DataTable({
ajax: {
url: baseurl + 'admin/Administrator/getdata_slider',
type: "POST"
},
processing: true,
serverSide: true,
columns: [{
data: "idHome",
visible: false
}, {
data: "jdlHome"
}, {
data: "isiHome",
sType: 'html'
}, {
data: "Actions",
searchable: false
}],
"order": [
[0, "asc"]
]
});
HTML Code :
<div class="box-body">
<div class="order-column">
<table id="dtslider" class="table table-striped table-bordered">
<thead class="dt-right">
<tr>
<th>id</th>
<th>Judul Panel</th>
<th>Isi Panel</th>
<th>Actions</th>
</tr>
</thead>
<tbody></tbody>
</table>
</div>
</div>
<!-- /.box-body -->
The output :
In image ouput there are strong at row2 and pre at row 3. I need to remove all html tags at the output. I already try something like sType and createdrow, but still no result. maybe because i am still new at DataTables and JavaScript. Can someone help me?
Edit (more code) :
getdata_slider :
public function getdata_slider()
{
$column = 'idHome, jdlHome, isiHome';
$id = 'idHome';
$table = 'home';
$columnwhere = 'ketHome';
$key = '1';
$this->Model_administrator->getDatatablesCustom2($column, $id, $table, $columnwhere, $key);
echo $this->datatables->generate();
}
getDatatablesCustom2 :
public function getDatatablesCustom2($column, $id, $table, $columnwhere, $key)
{
$this->load->library('Datatables');
$this->load->helper('Datatables_helper');
$this->datatables->select($column)->where($columnwhere, $key)
->unset_column('file')
->add_column('file','$1', 'file')
->add_column('Actions', get_buttons('$1'), $id)
->from($table);
}
I would use the columns.render-Option to manipulate the data before it is being rendered.
sType, createRow, and even columnRender didnt do anything for me. I don't know the fault is in library, jquery, or the stupid me (70% fault in the latter of course.).
but, thankfully, i found edit_column at library function.
my code now look something like this :
public function getDatatablesCustom2($column, $id, $table, $columnwhere, $key)
{
$this->load->library('Datatables');
$this->load->helper('Datatables_helper');
$this->datatables->select($column)->where($columnwhere, $key)
->unset_column('file')
->edit_column('isiHome', '$1', 'strip_tags(isiHome)')
->add_column('file','$1', 'file')
->add_column('Actions', get_buttons('$1'), $id)
->from($table);
}
thanks for all the pointer and help :)