Javascript DataTables warning, Requested unknown parameter 'Id' for row 0 - javascript

I'm getting the following error when I'm trying to fill a Datatable using ajax :
Also, I can get all datas in controller and i am returning Json from there. There is no any problem in controller. Just I can't fill datatable.
My javascript code in below :
This is my function
function createDatatable(setting) {
var actionsColumn = {
sortable: false,
searchable: false,
class: 'text-center',
render: function (data, type, row, meta) {
return '<a class="btn btn-outline-primary btn-sm" href="/' + setting.controller + '/Edit/' + row[setting.primaryKey] + '" title="Düzenle"><i class="icon-pencil"></i></a> <a class="btn btn-outline-danger btn-sm" href="/' + setting.controller + '/Delete/' + row[setting.primaryKey] + '" title="Sil"><i class="icon-trash"></i></a>';
}
};
if (setting.hasCostumActionsColumn === undefined || setting.hasCostumActionsColumn == false) {
setting.columns.push(actionsColumn);
}
if (setting.defaultSortingColumn === undefined) {
setting.defaultSortingColumn = 0;
}
if (setting.defaultSorting === undefined) {
setting.defaultSorting = "desc";
}
if (setting.queryString === undefined) {
setting.queryString = "";
}
var url = '/' + setting.controller + '/' + setting.action;
if (setting.queryString != undefined && setting.queryString != "") {
url += '?' + setting.queryString;
}
var table = $('#' + setting.tableId).DataTable({
info: false,
dom: '<"toolbar">frtip',
deferRender: true,
fnInitComplete: function () {
$("#table1_paginate").remove();
handlePaging();
$('#next-btn').on('click', function () {
table.page('next').draw('page');
updateCurrentPageInput();
});
$('#previous-btn').on('click', function () {
table.page('previous').draw('page');
updateCurrentPageInput();
});
$("#goto-page").on('click', function () {
var page = parseInt($("#pagination-current-page").val());
if (page < 1) {
page = 1;
} else if (page > table.page.info().pages) {
page = table.page.info().pages;
}
var index = page - 1;
table.page(index).draw('page');
updateCurrentPageInput();
});
$("#pagination-row-count").change(function () {
table.page.len($("#pagination-row-count").val()).draw();
updateCurrentPageInput();
});
},
"drawCallback": function (settings) {
updateCurrentPageInput();
},
responsive: true,
processing: true,
serverSide: true,
orderCellsTop: true,
autoWidth: true,
deferRender: true,
lengthMenu: [[10, 20, 50, 100, -1], [10, 20, 50, 100, "Tümü"]],
ajax: {
type: "POST",
url: url,
contentType: "application/json; charset=utf-8",
async: true,
headers: {
"RequestVerificationToken": document.querySelector('[name="__RequestVerificationToken"]').value
},
data: function (data) {
let additionalValues = [];
data.AdditionalValues = additionalValues;
return JSON.stringify(data);
}
},
columns: setting.columns,
columnDefs: setting.columnDefs,
order: [setting.defaultSortingColumn, setting.defaultSorting]
});
$("#filter-table").on('click', function () {
$(".table-filter").each(function (k, item) {
var index = $(item).data('index');
var val = $(item).val();
if (val != "") {
table.column(index + ':visible').search(val);
} else {
table.column(index + ':visible').search('DisableSearch');
}
});
table.draw();
});
$("#clear-filter-table").on('click', function () {
document.getElementById("filter-form").reset();
$(".table-filter").each(function (k, item) {
var index = $(item).data('index');
table.column(index + ':visible').search('');
});
table.draw();
});
$(".table-title").prependTo($("#table1_wrapper"));
function updateCurrentPageInput() {
console.log('table pager');
var currentPage = table.page() + 1;
$("#pagination-current-page").val(currentPage);
if (table.page() === 0) {
$('#previous-btn').attr("disabled", true);
} else {
$('#previous-btn').prop("disabled", false);
}
if (table.page.info().pages === currentPage) {
$('#next-btn').attr("disabled", true);
} else {
$('#next-btn').prop("disabled", false);
}
$("#pagination-current-page").prop('max', table.page.info().pages);
$("#table-info-div").html(`Toplam ${table.page.info().pages} sayfanın ${table.page() + 1}. sayfasındasınız. Toplam ${table.page.info().recordsTotal} kayıt bulunmaktadır.`);
}
function handlePaging() {
$('div.toolbar').html(`
<span id="table-info-div">Toplam2 ${table.page.info().pages} sayfanın ${table.page() + 1}. sayfasındasınız. Toplam ${table.page.info().recordsTotal} kayıt bulunmaktadır.</span>
<div class="input-group">
<button id="previous-btn" class="btn btn-success btn-sm paginate_button previous" style="margin-right:5px">< Önceki</button>
<input type="number" id="pagination-current-page" class="form-control" value="1" min="1" step="1" style="padding:5px; width:50px;margin-right:5px;" />
<button id="goto-page" class="btn btn-info btn-sm" style="margin-right:5px">Git</button>
<button id="next-btn" class="btn btn-success btn-sm paginate_button next" style="margin-right:5px">Sonraki ></button>
<div class="kayitSayisi">
<select id="pagination-row-count" class="form-control">
<option value="10">10</option>
<option value="25">25</option>
<option value="50">50</option>
<option value="100">100</option>
</select>
</div>
</div>`);
$("#pagination-current-page").prop('max', table.page.info().pages);
if (table.page() === 0) {
$('#previous-btn').attr("disabled", true);
} else {
$('#previous-btn').prop("disabled", false);
}
if (table.page.info().pages === 1) {
$('#next-btn').attr("disabled", true);
} else {
$('#next-btn').prop("disabled", false);
}
}
return table;
}
Here, I am calling the function :
createDatatable({
tableId: 'table1',
controller: 'User',
action: 'LoadTable',
columns: [
{
data: "Id",
name: "eq",
visible: true,
searchable: true
},
{
data: "FirstName",
name: "co",
searchable: true
},
{
data: "LastName",
name: "co",
searchable: true
},
{
data: "UserName",
name: "co",
searchable: true
},
{
data: "Email",
name: "co",
searchable: true
},
{
sortable: false,
class: 'text-center',
searchable: false,
render: function (data, type, row, meta) {
return '<a class="btn btn-outline-success btn-sm" href="/User/ChangePassword/' + row["Id"] + '" title="Şifre Değiştir"><i class="icon-lock"></i></a> <a class="btn btn-outline-primary btn-sm" href="/User/Edit/' + row["Id"] + '" title="Düzenle"><i class="icon-pencil"></i></a> <a class="btn btn-outline-danger btn-sm" href="/User/Delete/' + row["Id"] + '" title="Sil"><i class="icon-trash"></i></a>';
}
}
],
primaryKey: "Id",
hasCostumActionsColumn: true
});
Update :
I added html code :
<div class="content">
<div class="card-group-control card-group-control-right">
<div class="card">
<div class="card-header">
<h6 class="card-title">
<a data-toggle="collapse" class="collapsed text-default" href="#filter-collapse" style="display:block">Filtrele</a>
</h6>
</div>
<div id="filter-collapse" class="collapse">
<div class="card-body">
<form id="filter-form">
<div class="form-group row">
<div class="col-md-3">
<label class="col-form-label col-lg-12">Id</label>
<div class="col-lg-12">
<input type="text" class="form-control table-filter" data-index="0" />
</div>
</div>
<div class="col-md-3">
<label class="col-form-label col-lg-12">Adı</label>
<div class="col-lg-12">
<input type="text" class="form-control table-filter" data-index="1" />
</div>
</div>
<div class="col-md-3">
<label class="col-form-label col-lg-12">Soyadı</label>
<div class="col-lg-12">
<input type="text" class="form-control table-filter" data-index="2" />
</div>
</div>
<div class="col-md-3">
<label class="col-form-label col-lg-12">Kullanıcı Adı</label>
<div class="col-lg-12">
<input type="text" class="form-control table-filter" data-index="3" />
</div>
</div>
<div class="col-md-3">
<label class="col-form-label col-lg-12">E-Posta</label>
<div class="col-lg-12">
<input type="text" class="form-control table-filter" data-index="4" />
</div>
</div>
</div>
<div class="form-group row">
<div class="col-md-12">
<div class="col-lg-12">
Listele
Temizle
</div>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
<div class="card">
<div class="card-body">
<div class="table-title">Kullanıcılar</div>
<table id="table1" class="table table-bordered table-hover datatable-ajax datatable-responsive">
<thead>
<tr>
<th >Id</th>
<th data-priority="1">Adı</th>
<th data-priority="2">Soyadı</th>
<th>Kullanıcı Adı</th>
<th>E-posta</th>
<th style="width: 210px;"></th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
</div>
</div>

Related

DataTables warning: table id=datatable-crud - Invalid JSON response. For more information about this error, please see http://datatables.net/tn/1

Why i am getting this error DataTables warning: table id=datatable-crud - Invalid JSON response. For more information about this error, please see http://datatables.net/tn/1
The form for the search date to and from are as follows
#extends('layouts.app')
#section('content')
<div class="row">
<div class="col-lg-12 margin-tb">
<div class="pull-left">
</div>
<div class="pull-right m-1">
<!-- <a class="btn btn-primary" href="{{ route('perluhantars.index') }}"> Back</a> -->
</div>
</div>
</div>
#if ($errors->any())
<div class="alert alert-danger">
<ul>
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
#endif
<form action="{{ route('telahdihantars.store') }}" method="POST">
#csrf
<div class="card card-primary m-1" >
<div class="card-header">
Surat Keluar Yang Telah Dihantar
</div>
<div class="row">
<div class="col-xs-12 col-sm-12 col-md-12">
<div class="form-group">
<strong>Dari:</strong>
<input type="text" name="dari" id="dari" class="form-control" placeholder="Dari" value="">
</div>
</div>
<div class="col-xs-12 col-sm-12 col-md-12">
<div class="form-group">
<strong>Hingga:</strong>
<input type="text" name="hingga" id="hingga" class="form-control" placeholder="Hingga" value="">
</div>
</div>
<div class="col-xs-12 col-sm-12 col-md-12 text-center">
<button type="submit" class="btn btn-primary">Submit</button>
</div>
</div>
</div>
</form>
#endsection
#section('third_party_scripts')
<script type="text/javascript">
$( function() {
$( "#dari" ).datepicker({
dateFormat: "yy-mm-dd",
changeMonth: true,
changeYear: true
});
$( "#hingga" ).datepicker({
dateFormat: "yy-mm-dd",
changeMonth: true,
changeYear: true
});
});
</script>
#endsection
the store code is as follows:
public function store(Request $request)
{
$request->validate([
'dari' => 'required',
'hingga' => 'required',
]);
$dari = $request->dari;
$hingga = $request->hingga;
$documentouts = DB::table('documentouts')
->leftjoin('cawangans','documentouts.cawangan_id', '=', 'cawangans.id')
->leftjoin('kategoris', 'documentouts.kategori_id', '=', 'kategoris.id')
->leftjoin('peringkats', 'documentouts.peringkat_id', '=', 'peringkats.id')
->leftjoin('users as a' , 'documentouts.daripada' , '=', 'a.id')
->leftjoin('users as b', 'documentouts.penghantar_id', '=', 'b.id')
->select('documentouts.id','cawangans.cawangan as organisasi','kategoris.kategori as kategori','peringkats.peringkat as peringkat','documentouts.kepada', 'a.name as daripada', 'documentouts.tarikh_surat', 'documentouts.rujuk', 'documentouts.tajuk','b.name as penghantar', 'documentouts.penerima')
->whereBetween('tarikh_surat', [ $hingga , $dari ])->get();
// ->where('tarikh_surat', '>' , $dari )->get();
if(request()->ajax()) {
return datatables()->of($documentouts)
->addColumn('action', 'telahdihantars.action')
->rawColumns(['action'])
->addIndexColumn()
->make(true);
}
return view('telahdihantars.index2');
}
the telahdihantars.index2 code is as follows
#extends('layouts.app2')
#section('content')
<div class="row">
<div class="col-lg-12 margin-tb">
<div class="pull-left">
<h2>Surat Perlu Saya Hantar</h2>
</div>
<div class="pull-right m-1">
<!-- <a class="btn btn-success" href="{{ route('documentouts.create') }}"> Tambah Rekod</a> -->
</div>
</div>
</div>
#if ($message = Session::get('success'))
<div class="alert alert-success">
<p>{{ $message }}</p>
</div>
#endif
<div class="card-body">
<table class="table table-bordered" id="datatable-crud">
<thead>
<tr>
<th>Id</th>
<th>Organisasi</th>
<th>Kategori</th>
<th>Peringkat</th>
<th>Kepada</th>
<th>Daripada</th>
<th>Tarikh Surat</th>
<th>Rujuk</th>
<th>Tajuk</th>
<th>Penghantar Surat</th>
<th>Penerima</th>
<th>Action</th>
</tr>
</thead>
</table>
</div>
#endsection
#section('third_party_scripts')
<script type="text/javascript">
$(document).ready( function () {
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$('#datatable-crud').DataTable({
processing: true,
serverSide: true,
ajax: "{{ url('telahdihantars') }}",
columns: [
{ data: 'id', name: 'id' },
{ data: 'organisasi', name: 'organisasi' },
{ data: 'kategori', name: 'kategori' },
{ data: 'peringkat', name: 'peringkat' },
{ data: 'kepada', name: 'kepada' },
{ data: 'daripada', name: 'daripada' },
{ data: 'tarikh_surat', name: 'tarikh_surat' },
{ data: 'rujuk', name: 'rujuk' },
{ data: 'tajuk', name: 'tajuk' },
{ data: 'penghantar', name: 'penghantar' },
{ data: 'penerima', name: 'penerima' },
{data: 'action', name: 'action', orderable: false},
],
order: [[0, 'desc']]
});
$('body').on('click', '.delete', function () {
if (confirm("Padam rekod?") == true) {
var id = $(this).data('id');
// ajax
$.ajax({
type:"POST",
url: "{{ url('delete-documentout') }}",
data: { id: id},
dataType: 'json',
success: function(res){
var oTable = $('#datatable-crud').dataTable();
oTable.fnDraw(false);
}
});
}
});
});
</script>
#endsection
Apppreciate your help to solve the error.

Save ajax post data on div to localStorage

I created a datatable in which there is a button which has an action to post data into a div, below is the code I have:
html :
<div class="card-body">
<div class="overlay" id="kt_datatable_nodata">
<div class="overlay-wrapper rounded bg-light text-center pt-lg-30 pb-lg-30"
style="border: 2px dashed #c6c6c6;">
<p class="font-weight-bold text-center">Pilih data untuk dibandingkan.</p>
<a href='#left-modal' class='btn font-weight-bolder btn-jcm btn-md'
data-toggle='modal'>Pilih Data</a>
</div>
</div>
<div id="kt_datatable_fetch_display"></div>
</div>
This my datatable :
"use strict";
var LeftTable = function() {
var options = {
data: {
type: 'remote',
source: {
read: {
url: 'src/khu-pusat/json/compare.php',
},
},
},
columns: [{
field: 'name',
title: 'Name',
template: function(row) {
return row.nama_karyawan;
},
},{
field: 'proyek',
title: 'Proyek',
template: function(row) {
return row.proyek;
},
},{
field: 'action',
title: 'Action',
template: function(row) {
return '<button data-id="'+ row.id +'" class="btn btn-sm btn-jcm" type="button" data-dismiss="modal">Pilih</button>';
},
},]
};
var displayLeftData = function() {
$('#kt_datatable').on('click','tr button', function() {
var leftId = $(this).data('id');
$.ajax({
type: 'post',
url: 'src/khu-pusat/compare/left-side/left-value.php',
data: {
'rowid': leftId
},
success: function(data) {
$('#kt_datatable_nodata').addClass('hidden');
$("#kt_datatable_fetch_display").html(data);
}
});
}).click(function() {
$('#kt_datatable_fetch_display').empty();
});
};
return {
// public functions
init: function() {
displayLeftData();
},
};
}();
jQuery(document).ready(function() {
LeftTable.init();
});
left-value.php
<?php
include 'db_connect.php';
if (isset($_POST['rowid'])) {
$id = $_POST['rowid'];
$query = mysqli_query($config, "SELECT* FROM data_penilaian where id = '$id'");
$no = 1;
while ($row = mysqli_fetch_array($query)) {
?>
<div class="text-right">
<button type="submit" id="approve" class="btn btn-success btn-sm font-weight-bold"><i
class="flaticon2-paperplane"></i>Approve</button>
<a href='#left-modal' class='btn btn-light-success btn-sm font-weight-bold' data-toggle='modal'>Change more data</a>
</div>
<form class="leftForms" method="POST">
<h3 class="card-label">
<input type="hidden" name="id" class="form-control" value="<?= $row['id']; ?>">
<span class="d-block text-dark font-weight-bolder mb-5">
<i class="fa fa-genderless text-jcm mr-2"></i>
<?= $row['name']; ?>
</span>
<span class="d-block text-muted mt-1 font-size-sm ml-6">Proyek : <?= $row['proyek']; ?></span>
</h3>
</form>
<?php
}
}
?>
from the above case how can I save the data in kt_datatable_fetch_display into localStorage, in short, make kt_datatable_fetch_display into localStorage so that the div doesn't disappear when the page is reloaded.
You can use this code.
var displayLeftData = function() {
const content = localStorage.getItem('content');
if(content) {
$("#kt_datatable_fetch_display").html(content);
}
$('#kt_datatable').on('click','tr button', function() {
var leftId = $(this).data('id');
$.ajax({
type: 'post',
url: 'src/khu-pusat/compare/left-side/left-value.php',
data: {
'rowid': leftId
},
success: function(data) {
$('#kt_datatable_nodata').addClass('hidden');
$("#kt_datatable_fetch_display").html(data);
localStorage.setItem('content', data);
}
});
}).click(function() {
$('#kt_datatable_fetch_display').empty();
localStorage.removeItem('content');
});
};

Load DataTable data to a Edit Modal

I am trying to create an edit function for my data table. The data table is created using Yajra Data tables. Everything working fine unless when I try to load existing data into the edit modal it fails. No error is showing but the modal does not launch. I have only included a little portion of my code here for easy reference.
Modal:
<!-- Update Status Model Box -->
<div id="updateStatusModal" class="modal fade" role="dialog">
<div class="modal-dialog modal-lg">
<div class="modal-content bg-default">
<div class="modal-body">
<form class="form-horizontal" id="updateStatus">
#csrf
#method('PUT')
<div class="row">
<div class="col">
<div class="form-group text-center">
<h6 class="font-weight-bold">Stage 1</h6>
<label for="stage_1" class="switch">
<input type="checkbox" class="form-control" id="stage_1">
<div class="slider round"></div>
</label>
</div>
</div>
</div>
<div class="row">
<div class="col">
<div class="form-group">
<div class="col-md">
<label for="firstname">Coding</label>
<input type="text" class="form-control" id="first_name" value="" placeholder="Enter Completed Page Count">
</div>
</div>
</div>
</div>
</form>
</div>
<div class="modal-footer justify-content-between">
<button type="button" name="update_btn" id="update_btn" class="btn btn-outline-warning">Update</button>
</div>
</div>
</div>
</div>
jquery funtion:
// Edit action
$(document).on('click', '.updateStatus', function(){
$tr = $(this).closest('tr');
var data = $tr.clidren("td").map(function(){
return $(this).text();
}).get();
console.log(data);
$('#id').val(data[0]);
$('#job_id').val(data[2]);
$('#stage_1').val(data[3]);
$('#conversion').val(data[4]);
$('#updateStatusModal').modal('show');
});
I tried this method I found but this is not working. Can anyone provide me any pointers here?
I've just didn't seen your front scripts (also back-end codes), but instead I can share my implementation for that you need. It works perfectly like showed in this (screenshot).
Here I'll put front and back codes. There is functionality for editing existsing Datatable record, also record deletion.
FRONT
<!--HERE ATTACH NECESSARY STYLES-->
<!--VIEW end-->
<link rel="stylesheet" type="text/css" href="{{ asset('css/admin/datatables.min.css') }}"/>
<table id="yajra_datatable" class="table table-bordered">
<thead>
<tr>
<th>Name</th>
<th>Options</th>
</tr>
</thead>
</table>
<div class="modal modal-danger fade" id="modal_delete">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span></button>
<h4 class="modal-title">Delete Language</h4>
</div>
<div class="modal-body">
<p>Are You sure You want to delete this Language?</p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-outline pull-left" data-dismiss="modal">Cancel</button>
<button id="delete_action" type="button" class="btn btn-outline">Submit</button>
</div>
</div>
</div>
</div>
<div class="modal modal-warning fade" id="modal_edit">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span></button>
<h4 class="modal-title">Edit Language</h4>
</div>
<div class="modal-body">
<div class="form-group">
<label for="language_name">Language Name</label>
<input name="language_name" id="language_name" type="text" value="" class="form-control" placeholder="Language Name">
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-outline pull-left" data-dismiss="modal">Cancel</button>
<button id="edit_action" type="button" class="btn btn-outline">Submit</button>
</div>
</div>
</div>
</div>
<input type="hidden" id="item_id" value="0" />
<!--VIEW end-->
<!--HERE ATTACH NECESSARY SCRIPTS-->
<!--SCRIPTS start-->
<script src="{{ asset('js/admin/jquery.dataTables.min.js') }}"></script>
<script type="text/javascript">
var YajraDataTable;
function delete_action(item_id){
$('#item_id').val(item_id);
}
function edit_action(this_el, item_id){
$('#item_id').val(item_id);
var tr_el = this_el.closest('tr');
var row = YajraDataTable.row(tr_el);
var row_data = row.data();
$('#language_name').val(row_data.name);
}
function initDataTable() {
YajraDataTable = $('#yajra_datatable').DataTable({
"processing": true,
"serverSide": true,
"ajax": "{{ route('admin.book_languages.ajax') }}",
"columns":[
{
"data": "name",
"name": "name",
},
{
"data": "",
"name": ""
},
],
"autoWidth": false,
'columnDefs': [
{
'targets': -1,
'defaultContent': '-',
'searchable': false,
'orderable': false,
'width': '10%',
'className': 'dt-body-center',
'render': function (data, type, full_row, meta){
return '<div style="display:block">' +
'<button onclick="delete_action(' + full_row.id + ')" type="button" class="delete_action btn btn-danger btn-xs" data-toggle="modal" data-target="#modal_delete" style="margin:3px"><i class="fa fa-remove"></i> Delete</button>' +
'<button onclick="edit_action(this, ' + full_row.id + ')" type="button" class="edit_action btn btn-warning btn-xs" data-toggle="modal" data-target="#modal_edit" style="margin:3px"><i class="fa fa-edit"></i> Edit</button>' +
'</div>';
}
}
],
});
return YajraDataTable;
}
$(document).ready(function() {
var YajraDataTable = initDataTable();
$('#delete_action').on('click', function (e) {
e.preventDefault();
$.ajax({
url: "{{ route('admin.book_languages.delete') }}",
data: {
'item_id': $('#item_id').val(),
'_token': "{{ csrf_token() }}"
},
type: "POST",
success: function (data) {
$('#modal_delete').modal('hide');
YajraDataTable.ajax.reload(null, false);
console.log(data.message);
}
})
});
$('#edit_action').on('click', function (e) {
e.preventDefault();
$.ajax({
url: "{{ route('admin.book_languages.edit') }}",
data: {
'item_id': $('#item_id').val(),
'language_name': $('#language_name').val(),
'_token': "{{ csrf_token() }}"
},
type: "POST",
success: function (response) {
$('#modal_edit').modal('hide');
YajraDataTable.ajax.reload(null, false);
console.log(data.message);
}
})
});
$('#modal_delete').on('hidden.bs.modal', function () {
$('#item_id').val(0);
});
$('#modal_edit').on('hidden.bs.modal', function () {
$('#item_id').val(0);
$('#language_name').val("");
});
});
</script>
<!--SCRIPTS end-->
BACK
public function index() {
return view('admin.book-languages.index');
}
public function ajax() {
$items = BookLanguage::latest('id');
return DataTables::of($items)->make(true);
}
public function delete(Request $request) {
$item_id = $request->get('item_id');
$item = BookLanguage::find($item_id);
if(empty($item)) {
return response()->json([
'success' => false,
'message' => 'Item not found!',
], 200); // 404
} else {
$item->delete();
return response()->json([
'success' => true,
'message' => 'Item successfully deleted.',
], 200);
}
}
public function update(Request $request) {
$item_id = $request->get('item_id');
$item = BookLanguage::find($item_id);
if(empty($item)) {
return response()->json([
'success' => false,
'message' => 'Item not found!',
], 404);
} else {
$item->name = $request->get('language_name');
$item->save();
return response()->json([
'success' => true,
'message' => 'Item successfully updated.',
], 200);
}
}
ROUTES
// ...
// book_languages
Route::group(['prefix' => 'book-languages', 'as' => 'admin.book_languages.',], function () {
Route::get('all', 'BookLanguageController#index')->name('index');
Route::get('ajax', 'BookLanguageController#ajax')->name('ajax');
Route::post('update', 'BookLanguageController#update')->name('edit');
Route::post('delete', 'BookLanguageController#delete')->name('delete');
});
// ...
I think this can help you and others to build wanted functionality. Here this could be also with more hint-comments, but as it not small, I can answer later via post comments.
i am building a Laravel ERP-like web application and am implementing a CRUD function modal like you. I have made mine a server-side processing application with resource APIs in Laravel. Well, please be reminded that i have cut the #extends(layout.app) & #section('stylesheet') parts to go right into the answer. You should extend them in your own application to make everything work.
View.blade script
<script>
$(document).ready(function() {
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
var table = $('#customertable').DataTable({
processing: true,
serverSide: true,
dom: 'B<"top"frli>tp',
ajax: {
url: "{{ route('customer.index') }}", //Accessing server for data
columns: [
{data: 'id'}, //data refers to DB column name
{data: 'name'},
{data: 'chiname'},
{data: 'type'},
{data: 'action'}, //this is an addColumn item from Controller
]
});
$('#createNewcustomer').click(function () {
$('#saveBtn').val("create customer");
$('#customerid').val('');
$('#customerForm').trigger("reset");
$('#modelHeading').html("Create New Customer");
$('#customermodal').modal('show');
});
//Control the modal behavior when clicking the edit button.
$('body').on('click', '.editcustomer', function () {
var customerid = $(this).data('id');
$.get("{{ route('customer.index') }}" +'/' + customerid +'/edit', function (data) {
$('#modelHeading').html("Edit Customer");
$('#saveBtn').val("edit-user");
$('#customermodal').modal('show');
$('#customerid').val(data.id);
$('#name').val(data.name);
$('#chiname').val(data.chiname);
$('#type').val(data.type);
})
});
//Create a brand-new record
$('#createNewcustomer').click(function () {
$('#saveBtn').val("create customer");
$('#customerid').val('');
$('#customerForm').trigger("reset");
$('#modelHeading').html("Create New Customer");
$('#customermodal').modal('show');
});
//Update
$('body').on('click', '.editcustomer', function () {
var customerid = $(this).data('id');
$.get("{{ route('customer.index') }}" +'/' + customerid +'/edit', function (data) {
$('#modelHeading').html("Edit Customer");
$('#saveBtn').val("edit-user");
$('#customermodal').modal('show');
$('#customerid').val(data.id);
$('#name').val(data.name);
$('#chiname').val(data.chiname);
$('#type').val(data.type);
})
});
//Save
$('#saveBtn').click(function (e) {
e.preventDefault();
$(this).html('Sending..');
$.ajax({
data: $('#customerForm').serialize(),
url: "{{ route('customer.store') }}",
type: "POST",
dataType: 'json',
success: function (data) {
$('#customerForm').trigger("reset");
$('#customermodal').modal('hide');
table.draw();
},
error: function (data) {
console.log('Error:', data);
$('#saveBtn').html('Error');}
});
});
//Delete
$('body').on('click', '.deletecustomer', function () {
var id = $(this).data("id");
confirm("Are You sure?");
$.ajax({
type: "DELETE",
url: "{{ route('customer.store') }}"+'/'+id,
success: function (data) {
table.draw();
},
error: function (data) {
console.log('Error:', data);
}
});
});
</script>
View.blade html-table & modal part
#section('content')
<div class="container">
<div class="card-header border-left"><h3><strong> Customer overview</strong></h3></div>
<br>
<div class="row">
<div class="col-md text-right">
<button type="button" class="btn btn-success" data-toggle="modal" href="javascript:void(0)" id="createNewcustomer">Create Record</button>
</div>
</div>
{{-- Modal --}}
<div id="customermodal" class="modal fade" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title" id="modelHeading"></h4>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">&times</span></button></div>
<div class="modal-body">
<form id="customerForm" name="customerForm" class="form-horizontal">
<input type="hidden" name="customerid" id="customerid">
<div class="form-group">
<label for="name" class="col-sm-6 control-label">Customer Name</label>
<div class="col-sm-12">
<input type="text" class="form-control" id="name" name="name" placeholder="Name" value="" maxlength="50" required="">
</div>
</div>
<div class="form-group">
<label class="col-sm-6 control-label">Customer Name</label>
<div class="col-sm-12">
<input type="text" class="form-control" id="chiname" name="chiname" placeholder="Customer Name" value="" maxlength="50" required="">
</div>
</div>
<div class="form-group">
<label class="col-sm-6 control-label">Contract type</label>
<div class="col-sm-12">
<select name="type" id="type" class="form-control">
<option value="" disabled>Type</option>
<option value="Government">Government Contract</option>
<option value="Private">Private Contract</option>
</select>
</div></div>
<br>
<div class="col-sm text-right">
<button type="submit" class="btn btn-outline-secondary" id="saveBtn" value="create">Save changes</button>
</div>
</form>
</div>
</div>
</div>
</div>
{{-- Table --}}
<br>
<div class="row">
<br/>
<br/>
<div class="form-group col-md-12 align-content-center">
<table class="table-fluid center-block" id="customertable">
<thead>
<tr>
<th>id</th>
<th>ChiName</th>
<th>Name</th>
<th>Type</th>
<th>Action</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
</div>
</div>
#endsection
CustomerController
public function index(Request $request)
{
$customers = Customer::all();
}
return Datatables::of($customers)
->addColumn('action', function($customer){
$btn = 'Edit';
$btn = $btn.' Delete';
return $btn;})
->rawColumns(['action'])
->make(true);
}
return view('customer.Customer'); //my view blade is named Customer under customer dir. put your blade destination here.
}
public function store(Request $request)
{
Customer::updateOrCreate(['id' => $request->customerid],
['name' => $request->name, 'chiname' => $request->chiname,'type' =>$request->type]);
return response()->json(['success'=>'Product saved successfully.']);
}
public function edit($id)
{
$customer = Customer::findorfail($id);
return response()->json($customer);
}
public function destroy($id)
{
Customer::findorfail($id)->delete();
return response()->json(['success'=>'Product deleted successfully.']);
}
Model (pick either A.) $guarded = [] OR B.) $fillable = ['fields','fields'] as you like)
class Customer extends Model
{
protected $fillable = ['name','chiname','type'];
}
web.api (route setting)
Route::resource('customer', 'CustomerController')->middleware('auth');
Migration / DB schema structure
class CreateCustomersTable extends Migration
{
public function up()
{
Schema::create('customers', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('name');
$table->string('chiname');
$table->string('type');
$table->timestamps();
});
}
public function down()
{
Schema::dropIfExists('customers');
}
I have not included any protection in it like gate, auth or so. But basically this is the skeleton of doing CRUD with dataTable in Laravel framework with both JS, Ajax, Jquery, PHP all in one. Kindly be reminded that the queries for such CRUD actions are directly linked to the Database server. If you want to show data processed by the DataTable, use your own jquery function to fetch and show them on the modal. My answer is not the best but i hope it helps you >:)
(I could not post a picture to show you here as i dont have enough reputation lol. gg)

Unable to load a Knockout Component - Unknown template value: [object Object]

This is how I am using the component and sending the parameters using a Custom Element:
<div class="container" data-bind="with: DevoteeList">
<div class="row" style="padding: 10px;">
<div class="col-md-8"></div>
<div class="col-md-4">
<ko-pager params="Data: Devotees,
Modifier: $parent.DevoteeModifier,
PageCount: DevoteesPageCount(),
Url: '#Url.Action("SelectDevotees", "Devotee", new { a = 1 })'"></ko-pager>
</div>
</div>
This is how I am defining a Knockout Component. It is a Pager that I want to use at few places. But, I am receiving the error: Uncaught Error: Unable to process binding "with: function (){return SelectDevotees }"
Message: Unable to process binding "with: function (){return DevoteeList }"
Message: Unable to process binding "component: function () { return l }"
Message: Component 'ko-pager': Unknown template value: [object Object]
ko.components.register('ko-pager', {
viewModel: function (params) {
var self = this;
self.currentPage = ko.observable(1);
self.pages = ko.observableArray([]);
self.PageCount = ko.observable(params.PageCount);
//self.currentPage.subscribe(function (nv) {
// self.GetPage(self.parent);
//});
self.GetPages = function () {
for (var i = 1; i <= params.PageCount ; i++) {
self.pages.push(i);
}
return self.pages;
};
self.FirstPage = function () {
self.GetPage(1);
};
self.PrevPage = function () {
if (self.currentPage() > 1) {
var pn = self.currentPage() - 1;
self.GetPage(pn);
}
};
self.LastPage = function () {
self.GetPage(params.PageCount);
};
self.NextPage = function () {
if (self.currentPage() < params.PageCount) {
var pn = self.currentPage() + 1;
self.GetPage(pn);
}
};
self.GetPage = function (pg) {
if (pg == null)
pg = self.currentPage();
else
self.currentPage(pg);
var url = params.Url + '&pageNumber=' + pg;
$.get(url, function (data) {
var t = ko.mapping.fromJS(data);
if (params.Modifier) {
params.Modifier(t);
}
params.Data(t());
});
};
},
template: { element: document.getElementById('ko-ajax-pager') }
});
<div id="ko-ajax-pager" style="display: none;">
<div class="row" style="padding: 10px;" data-bind="visible: PageCount > 1">
<div class="col-md-1"></div>
<div class="col-md-2">
<input type="button" value="First" class="btn" data-bind="click: FirstPage" />
</div>
<div class="col-md-2">
<input type="button" value="Prev" class="btn" data-bind="click: PrevPage" />
</div>
<div class="col-md-2">
<select data-bind="options: GetPages(), value: currentPage, event: { change: GetPage(null) }">
</select>
</div>
<div class="col-md-2">
<input type="button" value="Next" class="btn" data-bind="click: NextPage" />
</div>
<div class="col-md-2">
<input type="button" value="Last" class="btn" data-bind="click: LastPage" />
</div>
<div class="col-md-1"></div>
</div>
</div>
Can someone please figure out, what is wrong?

Refresh jquery Data table

I am trying to refresh the create data table without reloading the whole page. So, everytime I try to search for a result, it will refresh the data table and give a new result and not add a new row instead. If i remove the $('#investmentTable').empty();. It gives me the all the result but it does not refresh my result
$('#investmentTable').empty(); only clears my data table completely and doesn't display any result
<div class="control-group">
<label class="control-label">Enter From Date</label>
<div style="width:40%" class="controls">
<input id="fromDate" type="text" name="fromDate" type="text" data-date-format="dd-mm-yyyy" class="datepicker span11">
</div>
</div>
<div class="control-group">
<label class="control-label">Enter To Date</label>
<div style="width:40%" class="controls">
<input id="toDate" type="text" name="toDate" type="text" data-date-format="dd-mm-yyyy" class="datepicker span11">
</div>
</div>
<div class="form-actions">
<input id="next" class="btn btn-primary" type="button"
value="Search" />
<div id="status"></div>
</div>
$("#next").on("click",function(event) {
$('#investmentTable').empty();
$.ajax({
type: 'POST',
url: app.api+'admin/report/date',
data: {
fromDate: $('#fromDate').val(),
toDate: $('#toDate').val()
},
success: function(data)
{
if (data.result == true) {
for(var i = 0; i < data.data.length; i++){
var item = data.data[i][0];
var x = $('#investmentTable').DataTable({
responsive: true,
bJQueryUI: true,
scrollX: true,
height: "100px",
display: "block",
sPaginationType: "full_numbers",
sDom: '<""l>t<"F"fp>'
});
x.row.add([item.date, item.name, item.email, item.contact.phone, item.account.investedAmount]);
x.draw();
}
}
},
return false;
});
Could you please move the code which creates table out of for loop. Please try below code.
$("#next").on("click",function(event) {
$('#investmentTable').empty();
$.ajax({
type: 'POST',
url: app.api+'admin/report/date',
data: {
fromDate: $('#fromDate').val(),
toDate: $('#toDate').val()
},
success: function(data)
{
if (data.result == true) {
var x = $('#investmentTable').DataTable({
responsive: true,
bJQueryUI: true,
scrollX: true,
height: "100px",
display: "block",
sPaginationType: "full_numbers",
sDom: '<""l>t<"F"fp>'
});
for(var i = 0; i < data.data.length; i++){
var item = data.data[i][0];
x.row.add([item.date, item.name, item.email, item.contact.phone, item.account.investedAmount]);
x.draw();
}
}
},
return false;
});

Categories

Resources