Datatable : Serverside global search does not send value in "search[value][0]" - jquery-plugins

I have Datatable with server-side (MVC.net) paging, sorting, column filter and global search as follows
Html code
<table id="Grid" class="dataTable table table-striped table-bordered " style="width: 100% !important">
<thead>
<tr>
<th>Name</th>
<th>Name2</th>
<th>name3</th>
<th>name4</th>
<th>name5</th>
<th></th>
<th></th>
<th></th>
<th></th>
<th>last name</th>
</tr>
</thead>
<tbody>
</tbody>
<tfoot>
<tr>
<th> <input class="form-control texts" type="text" placeholder="Filter Name" id="filter0" maxlength="180" /></th>
<th> <input class="form-control texts" type="text" placeholder="Filter Host" id="filter1" maxlength="180" /></th>
<th> <select class="form-control selects" id="filter2">
<option value="select">Select</option>
<option value="1">2</option>
<option value="2">2</option>
</select> </th>
<th>
<select class="form-control selects" id="filter3">
<option value="select">Select</option>
<option value="1">true</option>
<option value="2">false/option>
</select>
</th>
<th><select class="form-control selects" id="filter4">
<option value="select">Select</option>
<option value="True">True</option>
<option value="false">False</option>
</select>
</th>
<th>
<select class="form-control selects" id="filter5">
<option value="select">Select</option>
<option value="True">True</option>
<option value="false">False</option>
</select>
</th>
<th></th>
<th></th>
<th>
<div class='input-group date col-xs-9' id="datepicker2">
<input class="form-control datepicker texts" type="text" placeholder="Filter Key expiration date" id="filter8" maxlength="10" />
<span class="input-group-addon">
<span class="ebsi-icon-calendar"></span>
</span>
</div>
</th>
<th>
<div class="btn-group btn-group-xs pull-right">
<input id="btnColumnFilters" class="datatable-action btn btn-sm btn-primary btn-secondary" type="button" value="Filter"/>
<input id="btnClearColumnFilters" class="datatable-action btn-sm btn btn-grey btn-secondary" type="button" value="Clear"/>
</div>
</th>
</tr>
<tfoot>
</table>
javascript code :
var ConfigTable = $('#Grid')
.on('preXhr.dt', function(e, settings, data) {
$(".alert").hide(); // hide any alerts
})
.DataTable({
autoWidth: true,
lengthChange: false,
responsive: true,
searching: true,
ordering: true,
paging: true,
pageLength: 10,
serverSide: true,
order: [[0, "asc"]],
ajax: {
url: "/controller/action",
type: "POST",
datatype: "json",
error: function (xhr, error, thrown) {
},
data: function(d) {
return $.extend({},
d,
{
});
}
},
columns: [
{ "data": "Name", "name": "Name", "autoWidth": true, "searchable": true },
{ "data": "Name2", "title": "Name2", "name": "Name2", "autoWidth": true, "searchable": true }.....
]
});
Column filter on button click
//send column filter data on button click
$("#btnColumnFilters").click(function() {
filterColumns.map(function (key, value) {
ConfigTable = ConfigTable.column(key).search($("#filter" + key).val());
});
ConfigTable.draw();
});
//server side search only when user hits enter or previous input has been cleared
$('#Grid_filter input').unbind();
$('#Grid_filter input').bind('keyup', function(e) {
if (e.keyCode == 13 || $(this).val() == "") {
// clear all filter selection
resetColumnFilters();
//apply filters
ConfigTable.columns().search(this.value).draw();
}
});
server-side code
[HttpPost]
public JsonResult action(jQueryDataTableParamModel param)
{
//globla filter
var search = Request.Form.GetValues("search[value]")[0];
// column filter
var Name = Request.Form.GetValues("columns[0][search][value]")[0];
}
but I am not getting global search value in "Request.Form.GetValues("search[value]")[0]" on the server side. it always comes as an empty string. what might be the issue, please help.
I am using 1.10.2 version of datatable plugin.
Update 1:
Checked in network tab of firebug for ajax request, empty string is being sent for each request for search parameter, even if search value is there
search[value] : ""
Update 2:
If I remove code to send global filter value only when enter is hit, it sends the search value to server
Update 3:
alert on this.value gives a value but
ConfigTable.columns().search(this.value).draw(); does not send value to server

Found the solution. removed columns() while sending global filter
$('#Grid_filter input').bind('keyup', function(e) {
if (e.keyCode == 13 || $(this).val() == "") {
// clear all filter selection
resetColumnFilters();
//removed columns()
ConfigTable.search(this.value).draw();
}
});

Related

Ajax- DataTable Not Nowrking

I'm processing the incoming data with Ajax as follows. But I can't make it compatible with dataTable. I've read the Datatable Ajax documentation. But I was never successful. How do I pull the following data into the dataTable? I want to make these codes compatible for Data Table.
You can see multiple parse operations in my code. Please do not warn about it. Net Core, I can only process the JSON file in this way. The only thing I want from you is to show this data that I have processed successfully in the datatable.
<div class="card" id="view-maincategorylist">
<div class="card-body">
<div class="table-responsive">
<table id="datatablex" class="table table-striped table-bordered" style="width:100%">
<thead>
<tr>
<th class="text-center">Fotoğraf</th>
<th class="text-center">Ana Kategori Adı</th>
<th class="text-center">Seçenekler</th>
<th class="text-center">İşlemler</th>
</tr>
</thead>
<tbody id="table-maincategories">
</tbody>
</table>
</div>
</div>
</div>
<script>
function GetMainCategoryList() {
$.ajax({
url: "/Admin/BusinessCategories/MainCategories/",
contentType: "application/json",
dataType: "json",
type: "Get",
success: function (data) {
var item = jQuery.parseJSON(data);
$("#table-maincategories").empty();
$.each(JSON.parse("[" + item + "]"), (index, value) => {
for (let element of value) {
$("#table-maincategories").append(`<tr class="text-center">
<td><img src="${element.Image}" style="height:80px;" /></td>
<td>${element.Name}</td>
<td>
<div class="form-check">
<a href="/Admin/BusinessCategories/MainShowMenu/${element.Id}" onclick="location.href=this.href;">
<input class="form-check-input" type="checkbox" id="flex_${element.Id}">
</a>
<label class="form-check-label" for="flex_${element.Id}">Menüde Göster</label>
</div>
</td>
<td>
<a onclick="ShowEditMainCategory(${element.Id})" class="btn btn-primary"><i class="bx bx-edit"></i> Düzenle</a>
<a onclick="DeleteMainCategory(${element.Id});" data-name="${element.Name}" id="del_${element.Id}" class="btn btn-danger delete-button"><i class="bx bx-trash"></i> Sil</a>
</td> </tr>`);
var checkbox = document.getElementById('flex_' + element.Id);
if (element.ShowMenu == true) {
checkbox.checked = true;
}
else {
checkbox.checked = false;
}
}
});
$('#datatable').DataTable();
ViewShowHide(1);
},
error: function () {
Swal.fire('Veriler Okunamadı!', '', 'error')
}
})
}
</script>
Problem Images:
image 1
image 2
image 3
JSON Data Output:
https://easyupload.io/1bsb75

How to make filter on table based on option select

I am working on a project (vue + laravel) where i need to fetch all table structure from db. So my table will be dynamically with all field(table header) and record. Now i need to do a filter(search) for each visible column. I have tryed some way but it does not work for me, I just dont know how to pass only column value for each option select value.
Collapse content is the option who will show on filter click and there should display the option for each column
<table class="table table-hover align-middle mb-0" :class="smallTable.smTable">
<thead class="">
<tr>
<th><input type="checkbox" class="form-check-input" v-model="selectAll" title="Select All"></th>
<th v-for="(header, i) in visibleHeaders" :key="i" scope="col">
{{ header.name }}
</th>
<th v-if="actionHide">ACTION</th>
</tr>
</thead>
<!-- Collapsed content ./ -->
<thead class="collapse" id="collapseFilter">
<tr>
<th></th>
<th v-for="(header, i) in visibleHeaders" :key="i">
<div class="filter-table col-12 d-flex">
<select id="" class="form-select" >
<option v-for="(lead, i) in leads" >{{lead}}</option>
</select>
</div>
</th>
</tr>
</thead>
<!-- ./ Collapse contet -->
<tbody>
<tr v-show="leads.length" v-for="(lead, i) in leads" :key="i">
<td>
<input type="checkbox" class="form-check-input" v-model="selected" :value="lead.id" />
</td>
<td v-for="(field, j) in lead" :key="j">
<span v-if="field == 'new'" class="badge badge-primary">
{{ field }}
</span>
<span v-else-if="field == 'contract'" class="badge badge-success">
{{ field }}
</span>
<span v-else>
{{ field }}
</span>
</td>
<td >
<button #click="editLead(lead.id)" type="button" class="btn btn-sm btn-secondary" data-mdb-toggle="modal" data-mdb-target="#editLeadModal" >
<i class="fa-solid fa-eye"></i>
</button>
</td>
</tr>
<tr v-show="!leads.length">
<td colspan="12" class="text-center">Sorry :( No data found.</td>
</tr>
</table>
data() {
return {
headers: [],
leads: [],
fields: [],
}
}
mounted() {
axios.get('/leads/getfields')
.then(response => {
this.fields = response.data.map(field => {
return {
name: field,
visible: true,
}
});
}
this.getData();
});
}
getData() {
this.headers = this.fields.map(item => {
if (item.visible) {
return item.name;
}
});
axios.post('/leads/getleads?page=' + this.pagination.current_page, {
perPage: this.displayRecord,
fields: this.headers,
})
.then(response => {
this.leads = response.data.data;
this.pagination = response.data.meta
});
},

How to auto-populate form fields using vue and laravel

I'm developing a web application where I want to populate some field if I type computer_number I want to populate staff_old_name field that will select from staffs table.
This is what I've tried:
Template
<div>
<table class="table table-bordered table-hover">
<thead>
<tr>
<th>Computer Number</th>
<th>Old Name</th>
<th>New Name</th>
<th>Remarks</th>
<th>Action</th>
</tr>
</thead>
<tbody>
<tr v-for="(staff, index) in staffs">
<td>
<span v-if="staff.editmode"><input class="form-control" v-model="staff.computer_number"/></span>
<span v-else>{{staff.computer_number}}</span>
</td>
<td>
<span v-if="staff.editmode"><input class="form-control" v-model="staff.old_name"/></span>
<span v-else>{{staff.old_name}}</span>
</td>
<td>
<span v-if="staff.editmode"><input class="form-control" v-model="staff.new_name"/></span>
<span v-else>{{staff.new_name}}</span>
</td>
<td>
<span v-if="staff.editmode"><input class="form-control" v-model="staff.remarks"/></span>
<span v-else>{{staff.remarks}}</span>
</td>
<td>
<span v-if="!staff.editmode"><button class="btn btn-info" type="button" #click="edit(staff)">Edit</button></span>
<span v-else><button class="btn btn-success" type="button" #click="save(staff)">Save</button></span>
<span><button type="button" class="btn btn-danger" #click="remove(index)"><i class="fa fa-trash"></i></button></span>
</td>
</tr>
</tbody>
</table>
<div class="box-footer">
<button class="btn btn-info" type="button" #click="cloneLast">Add Row</button>
</div>
</div>
Script
export default {
data() {
return {
staffs: [],
data_results: []
}
},
computed:{
autoComplete(){
this.data_results = [];
if(this.computer_number.length > 2){
axios.get('/api/staffs/autocomplete',{params: {computer_number: this.computer_number}}).then(response => {
console.log(response);
this.data_results = response.data;
});
}
}
},
methods: {
edit :function(obj){
this.$set(obj, 'editmode', true);
},
save : function(obj){
this.$set(obj, 'editmode', false);
},
remove: function(obj){
this.staffs.splice(obj,1);
},
cloneLast:function(obj){
//var lastObj = this.staffs[this.staffs.length-1];
//lastObj = JSON.parse(JSON.stringify(lastObj));
obj.editmode = true;
this.staffs.push(obj);
},
},
created() {
axios.get('/staff-names')
.then(response => this.staffs = response.data);
},
}
when I type the computer number I want the staff_old_name field populated base on staff name which is stored in staffs table.

How to get value from Dynamic Dropdown and submit it in database in VueJs and Laravel

I am creating a form in which you add cities on the basis of countries you get from dynamic drop-down. I am able to get the category_id (foreign key) in Vuejs but I don't how to pass it to the laravel back-end. I want to create a subcategory object with name and category_id. category_id is foreign key. I am unable to get category_id and it is passing NULL to db.
**Category = Country**
**Subcategory = City**
<template id="add-post">
<div>
<table class="table">
<thead>
<tr>
<th>#</th>
<th>City Name</th>
<th>Country id</th>
</tr>
</thead>
<tbody>
<tr v-for="(subcategory, index) in citylist" :key="subcategory.id">
<td>{{ index + 1 }}</td>
<td>{{ subcategory.name }}</td>
<td>{{ subcategory.category_id }}</td>
</tr>
</tbody>
</table>
<h3>Add City</h3>
<form v-on:submit.prevent = "createPost">
<select v-model="countryid" name="country" class="form-control" #change="myFunction()">
<option countryid disabled>Select Country</option>
<option v-for="category in categories" v-bind:value='category.id' v-text="category.name">{{category.name}}</option>
</select>
<div class="form-group">
<label for="add-name">Name</label>
<input v-model="subcategory.name" class="form-control" required />
</div>
<button type="submit" class="btn btn-xs btn-primary">Add City</button>
<!-- <button v-on:click="setPostId()">click</button> -->
<router-link class="btn btn-xs btn-warning" v-bind:to="'/'">Cancel</router-link>
</form>
</div>
</template>
<script>
export default {
data: function () {
return {
categories: [],
category: '',
countryid:'',
subcategories: [],
subcategory: {name: '', category_id: ''}
};
},
mounted(){
this.loadCategories()
},
created: function() {
let uri = 'http://localhost:8000/cities/';
Axios.get(uri).then((response) => {
this.subcategories = response.data;
});
},
computed: {
citylist: function(){
if(this.subcategories.length) {
return this.subcategories;
}
}
},
methods: {
myFunction: function() {
console.log(this.countryid)
},
loadCategories(){
axios.get('/api/categories')
.then(response => this.categories = response.data)
.catch(error => console.log(error))
},
createPost: function() {
let uri = 'http://localhost:8000/addsubcategory/';
Axios.post(uri, this.subcategory).then((response) => {
this.$router.push({name: 'City'})
})
}
}
}
</script>
you can make drop down
<select v-model="fruit" id="deptList">
<option v-for="company_master in company_masters.data" v-bind:value="company_master.CompanyId"> {{company_master.CompanyName}}
</option>
</select>
and call the data with axios like
axios.get("api/company_master").then(response => (this.company_masters = response.data));
also define
company_masters:[],
fruit:'',

MVC3 ASP.NET Ajax BeginForm doesn't work sometimes when it's injected by other Ajax

I'm trying to have some Ajax form in the page which is not working at all, it does not send any requests on submit, noting in firebug, the form is being loaded to page by ajax, but I have other forms which are loaded to form by ajax into a jquery UI dialog and they are working fine, here is my whole partial view code , (the Part with action "SeacrhTasksTable" not working) I'd attach the rendered the whole HTML but it's so big.
#model APS.HelpDesk.UI.MyModel<APS.HelpDesk.Data.App_ProjectTask>
<h2>
پروژه
#ViewBag.ProjectTitle
</h2>
<div class="wrapperTask">
<div class="firstTask">
#* <input type="hidden" value="#(ViewBag.ProjectId)" />*#
#Ajax.ActionLink("تعریف کار جدید", "AddProjectTaskDialog", new
{
Id = ViewBag.ProjectId,
area = "ProjectAdmin"
}, new AjaxOptions()
{
HttpMethod = "GET",
LoadingElementId = "AddProjectTaskLoadingGif",
UpdateTargetId = "AddProjectTaskDialog",
InsertionMode = InsertionMode.Replace,
OnBegin = "clearDialogs();",
OnSuccess = " $('#AddProjectTaskDialog').dialog('open');"
}, new { id = "AddProjecTaskLink" })
بارگذاری مجدد جدول
</div>
<div class="secondTask">
<div id="AddProjectTaskLoadingGif" style="display: none;">
<img src="#Url.Content("~/Content/Images/ajax-loader/253L.gif")" alt="" />
</div>
</div>
</div>
<div id="test">
<table>
<tr>
<th>
#
</th>
<th>
کد کار
</th>
<th>
عنوان کار
</th>
<th style="min-width: 300px;">
مختصری از توضيحات
</th>
<th>
تاريخ ايجاد کار
</th>
<th>
مهلت انجام
</th>
<th>
وضعيت
</th>
<th>
وابستگی های کار
</th>
<th colspan="2">
ويرايش و حذف
</th>
</tr>
#using (Ajax.BeginForm("SeacrhTasksTable", new { area = "ProjectAdmin" }, new AjaxOptions
{
HttpMethod = "POST",
InsertionMode = InsertionMode.Replace,
UpdateTargetId = "test"
}))
{
<tr>
<td>
</td>
<td>
<input type="text" id="IdTask" style = "width:40px" name = "Id" />
</td>
<td>
<input type="text" id="TitleTask" style = "width:80%;" placeholder = "جست و جو" name = "Title" />
</td>
<td style="min-width: 250px;">
<input type="text" id="DescriptionTask" style = "width:80%;" placeholder = "جست و جو" name = "Description" />
</td>
<td>
<input type="text" id="DeliverDateTask" style = "width:80%;" placeholder = "جست و جو" name = "DeliverDate" />
</td>
<td>
<input type="text" id="DeadlineDateTask" style = "width:80%;" placeholder = "جست و جو" name = "DeadlineDate" />
</td>
<td>
<select name="Status">
<option value="0"> همه</option>
<option value="1">شروع نشده</option>
<option value="2">در حال انجام</option>
<option value="3">تمام شده</option>
<option value="4">بی مسئول</option>
</select>
</td>
<td colspan="4">
<input type="submit" value="submit" style="" />
<input type="hidden" value="#(ViewBag.ProjectId)" name="ProjectId" id ="ProjectIdTask"/>
</td>
</tr>
}
<tbody id="TaskList">
#Html.Partial("_ProjectTaskList", Model.MyList)
</tbody>
<tfoot>
<tr>
<td colspan="3">
صفحه
#(Model.PageIndex + 1)
از
#Model.TotalPages
[ تعداد کل : #Model.TotalCount ]
</td>
<td id="pagesizeTaskTd" style="text-align: center;">
سايز صفحه
<select id="pagesizeTask">
<option value="5">5</option>
<option value="10" selected="selected">10</option>
<option value="25">25</option>
<option value="50">50</option>
</select>
</td>
<td colspan="6" align="left" class="tfoot-padding" id="morepagesTask">
#{
int start = Model.PageIndex;
if (start > 0)
{
int c = 0;
while (start > 0 && c < 4)
{
c++;
start--;
}
}
for (int j = start; j < Model.TotalPages && j < start + 10; j++)
{
if (Model.PageIndex != j)
{
<span>
#Ajax.ActionLink((j + 1).ToString(), "TaskListTablePage", "Project", new
{
Id = ViewBag.ProjectId,
PageIndex = j,
PageSize = Model.PageSize,
area = "ProjectAdmin"
}, new AjaxOptions
{
HttpMethod = "GET",
UpdateTargetId = "test",
InsertionMode = InsertionMode.Replace
}, new { mode = "mode" })
</span>
}
else
{
<span><b style="text-decoration: underline;">#(j + 1)</b></span>
<input type="hidden" id="PIndexAll" value="#(j)" />
}
}
if (Model.PageIndex + 10 < Model.TotalPages)
{
<span>. . . </span>
}
}
</td>
</tr>
</tfoot>
</table>
</div>
<div id="AddProjectTaskDialog" title="تعریف کار جدید" style="text-align: right;">
</div>
<div id="EditProjectTaskDialog" title="ويرايش کار" style="text-align: right;">
</div>
<div id="ReportProjectTaskDialog" title="گزارش کل کار" style="text-align: right;">
</div>
<div id="DescriptionProjectTaskDialog" title="توضيح کار" style="text-align: right;">
</div>
<div id="EditProjectDepenDialog" style="text-align: right;">
</div>
<div id="Taskresult">
</div>
<script type="text/javascript">
$("#AddProjectTaskDialog").dialog({
autoOpen: false,
width: 720,
modal: true,
draggable: true,
position: "top"
});
$("#EditProjectTaskDialog").dialog({
autoOpen: false,
width: 720,
modal: true,
draggable: true,
position: "top"
});
$("#EditProjectDepenDialog").dialog({
autoOpen: false,
width: 720,
modal: true,
draggable: true,
position: "top",
buttons: {
"OK": function () {
$(this).dialog("close");
}
}
});
$("#AddProjecTaskLink").button();
$("#resetbutton").button();
$("#pagesizeTask").live( 'change' , function (){
var val = $(this).find(":selected").val();
$("#morepagesTask").find('*[mode]').each(function(index){
var n=$(this).attr("href").lastIndexOf("=");
var t= $(this).attr("href").substring(0,n+1);
$(this).attr("href" ,t+val );
});
var url = '#Url.Action("TaskListTablePage", new { area = "ProjectAdmin" })';
url += '?Id=' + #(ViewBag.ProjectId);
url += '&PageIndex=' + $("#PIndexAll").val();
url += '&PageSize=' +val;
$.ajax({
url: url, type: 'get',
success: function (data, status) {
$("#test").html('');
$("#test").html(data);
}
});
});
$(".firstTask").delegate( '#resetbutton','click',function(){
var url = '#Url.Action("TaskListTablePage", new { area = "ProjectAdmin" })';
url += '?Id=' + #(ViewBag.ProjectId);
url += '&PageIndex=0' ;
url += '&PageSize=10';
$.ajax({
url: url, type: 'get',
success: function (data, status) {
$("#test").html('');
$("#test" ).html(data);
}
});
});
</script>
HTML of Form
<form action="/ProjectAdmin/Project/SeacrhTasksTable" data-ajax="true" data-ajax-method="POST" data-ajax-mode="replace" data-ajax-update="#test" id="form0" method="post"> <tr>
<td>
</td>
<td>
<input type="text" id="IdTask" style = "width:40px" name = "Id" />
</td>
<td>
<input type="text" id="TitleTask" style = "width:80%;" placeholder = "جست و جو" name = "Title" />
</td>
<td style="min-width: 250px;">
<input type="text" id="DescriptionTask" style = "width:80%;" placeholder = "جست و جو" name = "Description" />
</td>
<td>
<input type="text" id="DeliverDateTask" style = "width:80%;" placeholder = "جست و جو" name = "DeliverDate" />
</td>
<td>
<input type="text" id="DeadlineDateTask" style = "width:80%;" placeholder = "جست و جو" name = "DeadlineDate" />
</td>
<td>
<select name="Status">
<option value="0"> همه</option>
<option value="1">شروع نشده</option>
<option value="2">در حال انجام</option>
<option value="3">تمام شده</option>
<option value="4">بی مسئول</option>
</select>
</td>
<td colspan="4">
<input type="submit" value="submit" style="" />
<input type="hidden" value="38" name="ProjectId" id ="ProjectIdTask"/>
</td>
</tr>
</form>
Your code doesn't work because you have invalid markup. By invalid markup I mean that you have a <form> nested directly inside a <tr> which is forbidden by the specification. You cannot have a <form> inside a <table>, <tbody> or <tr>.
To illustrate the problem in a simplified manner, here's what you have currently which is invalid:
<table>
<tr>
<form>
<td>Foo</td>
<td>Bar</td>
<td><input type="submit" /></td>
</form>
</tr>
</table>
Just inspect the DOM with FireBug and you will see how your <form> is floating alone (opening and closing immediately) without any elements inside.
This is invalid markup and it results in undefined behavior which in your case translates by the browser simply not submitting the form. The reason this happens is because the unobtrusive-ajax library that you are using subscribes to the submit event to all ajax forms using a .live:
$("form[data-ajax=true]").live("submit", function (evt) {
...
});
The thing is that the submit event is never raised in this case. A similar question has been asked yesterday with the same problem.
To fix this problem you could use nested tables:
<table>
<tr>
<td>
<form>
<table>
<tr>
<td>Foo</td>
<td>Bar</td>
<td><input type="submit" /></td>
</tr>
</table>
</form>
</td>
</tr>
</table>
So simply put your Ajax.BeginForm inside a <td> and then use a nested table to put the elements.

Resources