I have the following search box for getting data from backend:
<select class="form-control kt-select2" id="megaagent_rainmaker_select" name="param" multiple="multiple" style="width: 100%"></select>
This is my select2 javascript code:
var rainmakerSelect = function () {
// Private functions
var demos = function () {
var CSRF_TOKEN = $('meta[name="csrf-token"]').attr('content');
// multi select
$('#megaagent_rainmaker_select').select2({
language: "es",
placeholder: "Escriba y seleccione",
allowClear: true,
maximumSelectionLength: 1,
ajax: {
url: '/admin/megaagent/getrainmaker',
type: "get",
dataType: 'json',
delay: 150,
data: function (params) {
return {
_token: CSRF_TOKEN,
search: params.term // search term
};
},
processResults: function (response) {
return {
results: response
};
},
cache: true
}
});
}
return {
init: function () {
demos();
}
};
}();
jQuery(document).ready(function () {
rainmakerSelect.init();
});
I get results returned and I can select one without problem.
After I select a value, I send update request to backend, this is my payload:
{
"_token": "bPl0hZJQxw5wAxNCqVOOKqrXXwkD5AZZOFPumrpC",
"mc_id": "11",
"megaagent_id": "16",
"megaagent_name": "David Cortada",
"megaagent_business_name": "bsame cambio",
"megaagent_uma_id": "umaid",
"megaagent_api_key": "apikey",
"param": "963",
"megaagent_phone_number": "phone",
"megaagent_email": "email",
"megaagent_address": "address",
"megaagent_facebook": "fb",
"megaagent_instagram": "inst",
"megaagent_twitter": "twi",
"megaagent_linkedin": "link",
"megaagent_image": "image",
"megaagent_status": "Activo"
}
What I want to achieve is to change param name to other on post request (example: "megaagent_rainmaker_id" = "963",.
I changed it in <select name="param"> but that breaks the search, no results are returned when I type in search box.
Does anyone knows the solution for this?
Regards
Related
I have a admin login where the admin has to approve the student,I have used a toggle button for approval option, when clicked on the toggle button the value of status in database as to change from 1 to 0? How do I do this? Even if there are ways for it to work with normal buttons would also be helpful.Thank You.
<script type="text/javascript">
$(document).ready(function() {
$.noConflict();
fill_datatable();
function fill_datatable(collegeID = '') {
var table = $('.user_datatable1').DataTable({
order: [
[0, 'desc']
],
processing: true,
serverSide: true,
ajax: {
url: "{{ route('alumni.datatable1') }}",
data: {
collegeID: collegeID
}
},
columns: [{
data: 'id',
name: 'id'
},
{
data: 'name',
name: 'name'
},
{
data: 'status',
name: 'status',
mRender: function(data) {
return '<input data-id="{{$colleges->id}}" class="toggle-class" type="checkbox" data-onstyle="success" data-offstyle="danger" data-toggle="toggle" data-on="Approved" data-off="Pending" {{ $colleges->status ? "checked" : "" }}>'
}
},
{
data: 'action',
name: 'action',
orderable: false,
searchable: false
},
]
});
}
});
</script>
<script>
$(function() {
$(".toggle-class").change (function() {
var status = $(this).prop("checked")== true ? 0 : 1;
var id = $(this).data("id");
$.ajax({
type: "GET",
dataType: "json",
url: "/changeStatus",
data: {"status": status, "id": id},
success: function(data) {
console.log("Success")
}
});
});
});
</script>
Route
Route::get('changeStatus', [AdminAuthController::class, 'changeStatus'])->name('changeStatus');
Controller
public function changeStatus(Request $request,$regno)
{
$colleges = College::find($regno);
$colleges->status = $request->status;
$colleges->save();
return back();
}
I have used datatable individual column searching .
below is my js code:
var BindDataTable = function (response) {
var oTable;
$("#example").DataTable({
initComplete: function () {
// Apply the search
this.api().columns().every(function () {
var that = this;
$('input', this.footer()).on('keyup change clear',
function () {
if (that.search() !== this.value) {
that.search(this.value).draw();
}
});
});
},
"searching": true,
// dom: '<"class">Blfrtip',
dom: "<'row mb-3'<'col-sm-12 col-md-2 col-lg-2'l><'col-sm-12 col-md-10 col-lg-10 datatableButtonsCon text-right'Bf>>" +
"<'row'<'col-sm-12 datatablesData'tr>>" +
"<'row mt-4'<'col-sm-12 col-md-4 col-lg-6 infoCon'i><'col-sm-12 col-md-8 col-lg-6 pagCon'p>>",
"bServerSide": true,
"sAjaxSource": "/AspNetStudents/GetStudents",
"fnServerData": function (sSource, aoData, fnCallback) {
$.ajax({
type: "POST",
data:aoData,
url: sSource,
success:fnCallback
})
},
"aoColumns": [
{ "mData": "Name" },
{ "mData": "RollNo" },
{ "mData": "CellNo" },
{ "mData": "JoiningDate" },
{ "mData": "ClassName" },
{ "mData": "TotalWithoutAdmission" },
{ "mData": "UserStatus" },
]
});
oTable = $('#example').DataTable();
oTable.columns(0).search("data");
oTable.draw();
I have also attached the backend C# code to access the individual datatable column value to controller.
How can we access the datatable individual column searched value to controller(C# .net Mvc) while using the server side processing?
just as an idea, I know it makes ajax request every time a draw method is called.In this case, the data can be serialized and sent,then the searched data can be accessed by performing a parse operation in the controller.
$.ajax({
type: "POST",
dataType: "json",
url: sSource,
data: function (data) {
data.filters = $(".filter").serialize();
},
success:fnCallback
})
// search
$(".filter").on("change", function (e) {
e.preventDefault();
table.draw();
});
...
// in controller
// parse request
I want to implement individual form for ajax call. I want to have a command, which opens new popup window with one field, user fills this field and then clicks "Send" and then I do an ajax call to controller. My code:
$(document).ready(function () {
var grid = $("#memberList-grid").kendoGrid({
dataSource: {
type: "json",
transport: {
read: {
url: "#Html.Raw(Url.Action("MemberSearchList", "RandomPoolSelection"))",
type: "POST",
dataType: "json",
data: function () {
var data = {
SearchMember: $('##Html.IdFor(model => model.SearchMember)').val(),
SelectionId: $('#SelectionId').val()
};
addAntiForgeryToken(data);
return data;
}
}
},
schema: {
data: "Data",
total: "Total",
errors: "Errors"
},
error: function (e) {
display_kendoui_grid_error(e);
// Cancel the changes
this.cancelChanges();
},
pageSize: #(Model.PageSize),
serverPaging: true,
serverFiltering: true,
serverSorting: true
},
pageable: {
refresh: true,
pageSizes: [#(Model.AvailablePageSizes)],
#await Html.PartialAsync("_GridPagerMessages")
},
scrollable: false,
columns: [
{
field: "PrimaryID",
title: "#T("PoolMemberList.Fields.PrimaryID")",
width: 150
},
{
field: "FirstName",
title: "#T("PoolMemberList.Fields.FirstName")",
width: 150
},
{
command:
{
text: "Exclude",
click: showExclude
},
title: " ",
width: 100
}
]
});
wndExclude = $("#exclude")
.kendoWindow({
title: "Excuse Reason",
modal: true,
visible: false,
resizable: false,
width: 300
}).data("kendoWindow");
excludeTemplate = kendo.template($("#excludeTemplate").html());
});
function showExclude(e) {
e.preventDefault();
var dataItem = this.dataItem($(e.currentTarget).closest("tr"));
wndExclude.content(excludeTemplate(dataItem));
wndExclude.center().open();
}
and template :
<script type="text/x-kendo-template" id="excludeTemplate">
<div id="exclude-container">
<input type="text" class="k-input k-textbox" id="note">
<br />
</div>
</script>
how to implement sending this data (with ID) to controller?
A simple way to do what you want is using a partial view.
this is your command grid
{
command:
{
text: "Exclude",
click: showExclude
},
title: " ",
width: 100
}
and here your function :
function showExclude(e) {
$(document.body).append('<div id="excludeWindow" class="k-rtl"></div>');
var dataItem = this.dataItem($(e.currentTarget).closest("tr"));
$('#excludeWindow').kendoWindow({
width: "80%",
title: 'excludeForm',
modal: true,
resizable: false,
content: "/YourController/GetPartial?id=" + dataItem.Id,
actions: [
"Close"
],
refresh: function () {
$("#excludeWindow").data('kendoWindow').center();
},
close: function() {
setTimeout(function () {
$('#excludeWindow').kendoWindow('destroy');
}, 200);
}
}).data('kendoWindow');
}
After clicking on the button, you load your window(popup) and call an action that loads a partial view to fill the content of the window.
You can pass whatever you want to your partial view (for example, here I just send Id)
public ActionResult GetPartial(Guid id)
{
var viewModel= new ViewModelExclude
{
Id = id,
};
return PartialView("_exclude", viewModel);
}
and the partial view is something like this:
#model ViewModelExclude
#using (Html.BeginForm("", "Your action", FormMethod.Post, new { id = "SendForm"}))
{
<input class="k-rtl" name="#nameof(Model.Id)" value="#Model.Id">
<button type="submit" class="btn btn-primary">Send</button>
}
and then call Your ajax after clicking on send button:
$("#SendForm").submit(function (e) {
e.preventDefault();
var form = $(this);
var formData = new FormData(this);
$.ajax({
type: "POST",
url: '#Url.Action("send", "yourController"),
data: formData,
contentType: false,
processData: false,
success: function (data) {
},
error: function (data) {
}
});
});
Your send action something like this:
[HttpPost]
public ActionResult Send(ViewModelExclude view)
{
....
return Json();
}
I have the following Kendo MVVM grid:
<div id="permissionTypeGrid" data-role="grid"
data-sortable="true"
data-scrollable="true"
data-editable="true"
data-toolbar="['create', 'save', 'cancel']"
data-bind="source: permissionTypes"
data-auto-bind="true"
data-columns="[
{ 'field': 'PermissionType', 'width': 60 },
{ 'field': 'Description', 'width': 300 },
{ 'field': 'DisplayOrder', 'width': 60 },
{ 'command': [{name: 'destroy', text: 'Delete'}], 'width': 40 }
]">
</div>
And the following view model:
self.permissionTypeGrid = kendo.observable({
isVisible: true,
permissionTypes: new kendo.data.DataSource({
schema: {
parse: function (results) {
var permissionTypes = [];
for (var i = 0; i < results.Data.Data.length; i++) {
var permissionType = {
PermissionType: results.Data.Data[i].SystemPermissionTypeCode,
Description: results.Data.Data[i].SystemPermissionTypeDescription,
DisplayOrder: results.Data.Data[i].DisplayOrder
};
permissionTypes.push(permissionType);
}
return permissionTypes;
}
},
transport: {
read: {
url: "/api/ServiceApi?method=Ref/SystemPermissionTypes",
},
create: {
url: "/api/ServiceApi?method=Ref/SystemPermissionTypes"
},
update: {
url: "/api/ServiceApi?method=Ref/SystemPermissionTypes"
},
destroy: {
url: "/api/ServiceApi?method=Ref/SystemPermissionTypes"
},
parameterMap: function (options, operation) {
if (operation !== "read" && options.models) {
return { models: kendo.stringify(options.models) };
}
}
}
})
});
kendo.bind($("#permissionTypeGrid"), self.permissionTypeGrid);
Transport.read works fine, but the url for transport.create is never executed, nor is the parameterMap function. If I add a new record to the grid and then click "Save Changes", shouldn't the parameterMap function always be called? Also, an http request for the read is made as expected, but none gets generated for a create.
You schema needs and ID.
If you add the line model: { id: "DisplayOrder" }, after schema your create will begin firing when you click save changes.
Of course this is not likely to be the field that you will want to use for an ID but it should get you working.
schema: {
model: { id: "DisplayOrder" },
parse: function (results) {
...
}
I am trying to setup Select2 to use Ajax and am rather stuck. I have debugged in IE and confirmed that my AJAX is returning results, so that doesn't appear to be the issue. The input box loads, but when I type "mi" in for "milk" it just says "searching..." and never finds anything!
Here is my Jquery:
$(document).ready(function () {
$('#e1').select2({
placeholder: "Select an ingredient...",
minimumInputLength: 2,
ajax: {
url: "../api/IngredientChoices",
dataType: "jsonp",
quietMillis: 500,
data: function (term, page) {
return {
q: term,
page_limit: 10,
page: page
};
},
results: function (data, page) {
var more = (page * 10) < data.total;
return {
results: data.MainName, more:more
}
}
}
});
});
JSON:
[{"SubItemID":1,"MainItemID":1,"SubName":"2%","MainName":"Milk"},{"SubItemID":2,"MainItemID":1,"SubName":"Skim/Fat Free","MainName":"Milk"},{"SubItemID":3,"MainItemID":2,"SubName":"Chedder","MainName":"Cheese"}]
HTML:
<td><input type="hidden" id="e1" /></td>
If I change the dataType to be just json I get a different kind of error when I type "mi" into the box.
Here is the final code for the working version:
$('#e1').select2({
placeholder: "Select an ingredient...",
minimumInputLength: 2,
ajax: {
url: "../api/IngredientChoices",
dataType: "json",
quietMillis: 500,
data: function (term, page) {
return {
q: term,
page_limit: 10,
page: page
};
},
results: function (data, page) {
var more = (page * 10) < data.length;
console.log(more);
console.log(data);
return { results: data, more: more };
},
formatResult: function (post) {
markup = '<strong>' + post.text + '</strong>';
}
}
});
The error you are encountering appears to be because of the format of the results you are getting. Select2 is expected results to be a collection of objects with id: and text: attributes.
[{ id: 1, text: 'String' }, { id: 2, text: 'Other String.'}]