i have problem with duplicate position in datatables.
I have table with orders
id | order_no | status | etc.
and second table with order owners. Each order can have several owners.
In laravel controller i have code like this:
$orders = DB::table('orders')
->join('order_addresses', 'orders.id', '=', 'order_addresses.order_id')
->join('customers', 'orders.id_client', '=', 'customers.id')
->join('order_owners', 'orders.id', '=', 'order_owners.order_id')
'users.name as username', 'orders.comment', 'order_addresses.country')
->select('orders.id', 'orders.order_no', 'orders.deadline', 'customers.name as customersname', 'orders.comment', 'order_addresses.country')
->get();
return Datatables($orders)->make(true);```
and in view this
var url = "orders/show";
var table = $('#orders').DataTable({
"processing": true,
"serverSide": true,
"ajax": {
"dataType": "json",
"url": url,
"data": function(outData) {
// what is being sent to the server
console.log('i');
console.log(outData);
return outData;
},
dataFilter: function(inData) {
// what is being sent back from the server (if no error)
console.log('i2');
console.log(inData);
return inData;
},
error: function(err, status) {
// what error is seen(it could be either server side or client side.
console.log('i3');
console.log(err);
},
},
"columns": [{
sortable: false,
"render": function(data, type, full, meta) {
return '<span class="badge badge-danger"></span>';
}
},
{
"name": "id",
"data": ".id"
},
{
"name": "order_no",
"data": "order_no"
},
{
"name": "deadline",
"data": "deadline"
},
{
"name": "customersname",
"data": "customersname"
},
{
"name": "country",
"data": "country"
},
{
"name": "comment",
"data": "comment"
},
{
sortable: false,
"render": function(data, type, full, meta) {
var buttonID = full.id;
return 'edit';
}
},
],
});
When i add 2 owners in order i get duplicate datatables
So, how i can add in one column this 2 owners in one row?
Related
I am mounting a table and perfect until I want to show more data, I have read that I can use server side but I have not found any example how to consume an web service that returns json
html
<table id="datatable-buscador" class="display nowrap" style="width:100%">
<thead>
<tr>
<th>NÂș reco.</th>
<th>Fecha</th>
<th>Id trabajador</th>
<th>Trabajador</th>
<th>Id empresa</th>
<th>Ref. Int.</th>
<th>Nombre empresa</th>
<th>Visado</th>
<th>Prop.</th>
</tr>
</thead>
</table>
javascript
let $tabla = jQuery("#datatable-buscador");
$tabla.dataTable().fnDestroy();
$tabla.dataTable({
"scrollX": true,
"lengthMenu": [[15, 25, 30, -1], [15, 25, 30, "All"]],
"lengthChange": false,
"order": [1, "desc"], //columna 0 y ordenar desc
"language": { "url": "/src_reconocimientos/includes/js/utils/spanish.json" },
"ajax": {
url: "/example/example.php",
type: "POST",
dataType: "JSON",
data: { "tipo": tipo, "dias_reco": diasReco },
timeout: 180000 //3 min
},
"createdRow": function (row, data, dataIndex) {
jQuery(row).attr("id", data.N_RECONOCIMIENTO);
},
"columnDefs": [
{
// targets: "_all",
targets: [0, 1, 2, 4, 5, 7, 8],
className: 'dt-body-center'
},
],
"columns": [
{ "data": "N_RECONOCIMIENTO" },// 0
{
"data": null,
render: function (data, type, full, meta) {
return formatFecha(data.FECHA_RECONOCIMIENTO);
}
}, //1
{ "data": "DNI" }, // 2
{ "data": "NOMBRE_TRABAJADOR" }, // 3
{ "data": "EMPRESA" }, // 4
{ "data": "REF_INTERNA" }, // 5
{ "data": "NOMBRE_CLIENTE" }, // 6
{ "data": "VISADO" }, // 7
{ "data": "PROP" }, // 8
]
});
json:
{
"data": [{
"N_RECONOCIMIENTO": 29457,
"FECHA_RECONOCIMIENTO": "2021-10-11",
"DNI": "28460Q",
"NOMBRE_TRABAJADOR": "CAMPS",
"EMPRESA": 112390,
"REF_INTERNA": "Ref_interna?",
"NOMBRE_CLIENTE": "example",
"VISADO": "N",
"PROP": "Prop?"
}, {
"N_RECONOCIMIENTO": 2907,
"FECHA_RECONOCIMIENTO": "2021-10-14",
"DNI": "414J",
"NOMBRE_TRABAJADOR": "CARLOS",
"EMPRESA": 103482,
"REF_INTERNA": "Ref_interna?",
"NOMBRE_CLIENTE": "(ACUERDO DE COLABORA)",
"VISADO": "N",
"PROP": "Prop?"
}, {
"N_RECONOCIMIENTO": 2619,
"FECHA_RECONOCIMIENTO": "2021-04-16",
"DNI": "72306W",
"NOMBRE_TRABAJADOR": "DIEZ",
"EMPRESA": 29514,
"REF_INTERNA": "Ref_interna?",
"NOMBRE_CLIENTE": "example 365, S.L.",
"VISADO": "S",
"PROP": "Prop?"
}]
}
when pointing to the url of the ajax what it returns me is a json that changes the content according to the data that I pass to it, but when I want to get more 50000 records, the table fails me, so I want to implement serverside, how can I implement it and keep pointing the same url? I don't see anything related in the datatables examples
add info:
It is a very simple company webservice that receives data through my php script with cURL, in this it receives a type of request (it can be 1, 2, 3) and receives parameters (variables), the web services does the queries, simple queries and returns the result as json, it cannot be interacted any more, that's why when I try to process 50000 the datatable gives me an error. my question is: how can I do an intermediate step to process so many lines?
I am trying to populate a already built php database using axios requests, however i keep receiving 422 error and I don't understand what I am missing. Could you please help me :)
This is the error that i get:
xhr.js:177 POST URL/data 422 (Unprocessable Entity)
This is the Post request schema of the DB:
"post": {
"summary": "Post new data row",
"description": "Post new data row",
"requestBody": {
"required": true,
"content": {
"application/json": {
"schema": {
"type": "object",
"properties": {
"data": {
"type": "string",
"example": "{\"test\":1}"
},
"type": {
"type": "string",
"example": "1"
},
"status": {
"type": "integer",
"example": 1
}
},
"required": [
"data",
"type"
]
}
}
}
},
"responses" :{
"422": {
"description": "Error",
"content": {
"application/json": {
"schema": {
"type": "array",
"items": {
"type": "object",
"properties": {
"error": {
"type": "string",
"example": "Invalid input"
}
This is my code,
I have several switch cases and they should all work in the same manner:
case "rezervariContact" : {
const {type, titlu, description, phone, email} = this.state;
const contactData = {
type: this.state.type,
data:{
type,
data :{
titlu, description, phone, email
}
},
status:true
}
data = {...contactData};
}
}
await axios({
method: "post",
headers: { "Content-Type": "application/json",
'Accept': '*/*' },
body:data,
url : 'http://xxxxxxxxx.ro/data'
})
.then(function (response) {
console.log("RespResolved::",response.config.params);
})
.catch(function (response) {
console.log("catchErrResp::",response);
});
}
Please if you can spot something let me know.
422 probably means your inputted data is invalid.
The reason for this depends on the server. You could try referring to any documentation for the API/server you are trying to reach.
Check document on http://xxxxxxxxxx.ro/data! It means your post data is valid but server can not hand it correctly!
I'm using Laravel 5.6, PHP 7.1, XAMPP. I have URL which contain a values from one controller and defined before.
My question, how to get the last value in laravel URL without passing a value before. My code below will show the problem as well.
This is my Ajax:
$(document).ready(function() {
$('#student_table').DataTable({
"processing": true,
"serverSide": true,
"ajax": "{{ route('leads.getdata') }}",
"columns":[
{ "data": "group_id" },
{ "data": "customer_id" },
{ "data": "customer_id" },
{ "data": "action", orderable:false, searchable: false},
{ "data":"checkbox", orderable:false, searchable:false}
]
});
My route:
Route::get('leads/getdata', 'Controller#getdata')->name('leads.getdata');
Controller.php
function getdata(Request $request)
{
//$id = $request->input('id');
$students = GroupCustomer::select('id', 'name', 'address')->where('user_id', '=', $id);
return Datatables::of($students)
->addColumn('action', function($student){
return '<i class="glyphicon glyphicon-eye-open"></i><i class="glyphicon glyphicon-remove"></i>';
})
->addColumn('checkbox', '<input type="checkbox" name="student_checkbox[]" class="student_checkbox" value="{{$id}}" />')
->rawColumns(['checkbox','action'])
->make(true);
}
The current URL is : http://localhost:8000/leads/6 as I need to get '6' value and pass it to the query to get the name, address of that user. currently, it working without 'where' statement. However, I want to show only the name and address of user_id = '6'.
Is there a way to get this '6' value without change anything in Ajax and route as well ?
Change route to:
Route::get('leads/{id}', 'Controller#getdata')->name('leads.getdata');
Change controller to:
function getdata(Request $request, $id) {
//$id = $request->input('id');
$students = GroupCustomer::select('id', 'name', 'address')->where('user_id', '=', $id)->get();
return Datatables::of($students)
->addColumn('action', function($student){
return '<i class="glyphicon glyphicon-eye-open"></i><i class="glyphicon glyphicon-remove"></i>';
})
->addColumn('checkbox', '<input type="checkbox" name="student_checkbox[]" class="student_checkbox" value="{{$id}}" />')
->rawColumns(['checkbox','action'])
->make(true);
}
I think it's not possible to achieve what you want without touching ajax or route.
the problem was solved by binding the data, actually the problem was from binding the data. Dom . was not working well so once I fix the problem of binding it working well.
this is my Ajax code after fix the problem of DOM :
var id = document.getElementById("customer_id").value;
$('#student_table').DataTable({
"processing": true,
"serverSide": true,
ajax: {
url: "{!! route('leads.getdata') !!}",
type: "GET",
data: {id, id},
dataType: "JSON"
},
"columns":[
{ "data": "group_id" },
{ "data": "customer_id" },
{ "data": "customer_id" },
{ "data": "action", orderable:false, searchable: false},
{ "data":"checkbox", orderable:false, searchable:false}
]
});
Thanks
Free jqGrid uses data in the following JSON name:value pairs format:
var data = {
"page": "1",
"records": "3",
"rows": [
{ "DataID": "1", "DataDesc": "Test 1", "DataTitle": "Test 1" }
]
};
I have the following in the PHP script:
$i=0;
while ($row = mysql_fetch_assoc($result)) {
$data->rows[$i]['cell']=array($row);
$i++;
}
print json_encode($data);
Which returns:
{"rows":[{"cell":[{"user_id":"00082563","first_name":"Peter","case_title":"Male with STI (urethritis)","case_started":"2017-06-02 10:52:10"}]}]}
Which looks to be OK. However, with the JSON parts of the code below, the grid doesn't display at all.
function loadFirstGrid() {
$("#FirstGrid").jqGrid({
url: "scripts/json_test.php?user=" + user,
dataType: "json",
mtype: "GET",
postData: {
json: JSON.stringify(data)
},
colModel: [{
name: "user_id",
label: "User ID",
width: 120
},
{
name: "first_name",
label: "Name",
width: 400
},
{
name: "case_title",
label: "Case Title",
width: 500
},
{
name: "case_started",
label: "Case Started",
width: 200
},
],
emtyrecords: "Nothing to display",
viewrecords: true,
sortable: true,
shrinkToFit: false,
autowidth: true,
caption: 'First Grid'
});
}
But if I remove the postData part to have the following, the grid displays, but of course no data.
function loadFirstGrid() {
$("#FirstGrid").jqGrid({
url: "scripts/json_test.php?user=" + user,
dataType: "json",
mtype: "GET",
colModel: [{...
Any ideas?
OK, finally worked through this and got it working with this
function loadFirstGrid() {
$("#FirstGrid").jqGrid({
url: "scripts/json_test.php?user=" + user,
dataType: "json",
mtype: "GET",
colModel: [
{name: "user_id", label:"User ID", width: 120},
{name: "first_name", label:"Name", width: 400},
{name: "case_title", label:"Case Title", width: 500},
{name: "case_started", label:"Case Started", width: 200},
],
emtyrecords: "Nothing to display",
viewrecords: true,
sortable: true,
shrinkToFit: false,
autowidth: true,
caption: 'First Grid',
});
}
To get the correct format JSON for jqGrid:
{"page":"1","total":"1","records":"1","rows":[{"user_id":"00082563","first_name":"Peter","case_title":"Male with STI (urethritis)","case_started":"2017-06-02 10:52:10"}]}
I used the following PHP script:
$page = '1';
$total_pages = '1';
$count = '1';
$data = (object) array('page' => $page, 'total' => $total_pages, 'records' =>$count, 'rows' => "");
$data->page = $page;
$data->total = $total_pages;
$data->records = $count;
$i=0;
while ($row = mysql_fetch_assoc($result)) {
$data->rows=array($row);
$i++;
}
print json_encode($data);
?>
(NOTE: I don't care about the number of pages, total_pages and count as my grids will only ever have one primary record and multiple subgrids with only one record). So hope this helps someone; there is not much in the documentation or examples that describes how to do this with Free jqGrid ;-(
First of all JavaScript is case sensitive language and jqGrid will ignore parameter dataType: "json". You should fix it to datatype: "json".
Seconds, you use exotic format of the JSON data:
{
"rows": [{
"cell": {
"user_id": "00082563",
"first_name": "Peter",
"case_title": "Male with STI (urethritis)",
"case_started": "2017-06-02 10:52:10"
}
}]
}
instead of
{
"rows": [ {
"user_id": "00082563",
"first_name": "Peter",
"case_title": "Male with STI (urethritis)",
"case_started": "2017-06-02 10:52:10"
}]
}
or
[ {
"user_id": "00082563",
"first_name": "Peter",
"case_title": "Male with STI (urethritis)",
"case_started": "2017-06-02 10:52:10"
}]
You don't use loadonce: true and it's unclear, whether you plan to implement server side paging, sorting and filtering of data or you want to return all the data at once and jqGrid should use client side paging, sorting and filtering.
Finally, you should use name properties of colModel corresponds to the properties of user_id. It's very important to understand, that jqGrid have to assign unique id to every row of the grid (see here). Thus you have to inform jqGrid, which property contains rowid. You can use either jsonReader: { id: "user_id" } or to include property key: true in the column user_id.
The demo https://jsfiddle.net/OlegKi/qgrwymuu/1/ contains an example of described above modifications. It uses Echo service of JSFiddle to simulate server, which responses with some JSON data.
I am using DataTable to display the data. All the column names with check box is displaying when i click show and hide button. When i uncheck all the column and when i try to check the column name at that time the first column is getting copied or getting displayed in the all the row values.
Following is my code which i written.
$('#datatable_col_reorder').dataTable({
"processing": true,
"sAjaxSource": "<?php echo $config['ajaxUrlPath'];>json.php",
"bFilter" : true,
"fnServerData": function ( sAjaxSource , aoData, fnCallback ) {
aoData.push( { "name": "eventName", "value": $('#eventName').val() });
aoData.push( { "name": "et", "value": $('#Type').val() });
aoData.push( { "name": "vn", "value": $('#address').val() });
aoData.push( { "name": "da", "value": $('#date_added').val() });
aoData.push( { "name": "ti", "value": $('#time_added').val() });
aoData.push( { "name": "st", "value": $('#status').val() });
aoData.push( { "name": "br", "value": $('#status1').val() });
aoData.push( { "name": "cr", "value": $('#status2').val() });
aoData.push( { "name": "pr", "value": $('#spercentage').val() });
// etc
$( "#status2,#address,#spercentage" ).keyup(function() {
var table = $('#datatable_col_reorder').DataTable();
table.ajax.reload();
});
$( "#status,#Type,#date_added,#time_added,#status1,#status2" ).change(function() {
var table = $('#datatable_col_reorder').DataTable();
table.ajax.reload();
});
$.getJSON( sAjaxSource, aoData, function (json) { console.log(json); fnCallback(json) } );
},
"sDom":"<'col-sm-1 col-xs-1 col-md-1 col-lg-1 showHidebutton'C><'dt-toolbar'r>"+
"t"+
"<'dt-toolbar-footer'<'col-sm-6 col-xs-12 hidden-xs'i><'col-sm-6 col-xs-12'p>>",
"autoWidth" : true,
"rowCallback": function( nRow, aData, iDisplayIndex ) {
// responsiveHelper_datatable_tabletools.createExpandIcon(nRow);
$('td:eq(0)', nRow).html(''+aData[0]+'');
return nRow;
},
"preDrawCallback" : function() {
// Initialize the responsive datatables helper once.
if (!responsiveHelper_datatable_col_reorder) {
responsiveHelper_datatable_col_reorder = new ResponsiveDatatablesHelper($('#datatable_col_reorder'), breakpointDefinition);
}
},
"drawCallback" : function(oSettings) {
responsiveHelper_datatable_col_reorder.respond();
}
});
When i uncheck all and when i try to recheck each checkboxes, at that time the first column values are getting displayed in all other column like type,status,address etc.
Example: Consider Name: XYZ, After deselecting checkboxes if i try to recheck at that time the each column values is showing "XYZ" in status,address columns.
Thanks in advance.