How to post data from jquery datatable - javascript

I need to bind jquery dataTable using handler and I am sending parameters to that handler which is through object log given below.On button click I am calling the a function in which I have written the below code. On clicking on the button I need to have the datatable.But the problem is that I am unable to bind the jquery datatable. Please help.
Is there anyway to pass log as parameter to jquery datatable call and capture that in handler?
var log = { LogType: logType, InstanceID: instanceId, StartDateTime: StartDateTime, EndDateTime: EndDateTime, UserId: UserId, SearchKey: SearchValue, ProjectID: projectId, ClassID: ClassId, MethodID: MethodId, UserName: UserName, FilePath: FilePath };
$.ajax({
url: "LogManager.ashx",
dataType: "json",
responseType: "json",
data: { searchlog: JSON.stringify(log) },
success: function (data) {
$('#tblLogTable').DataTable({
"data": data,
"columns": [
{ 'data': "stProjectName" },
{ 'data': "stMethodName" },
{ 'data': "stUserName" },
{ 'data': "stFilePath" },
{ 'data': "stClassName" },
{ 'data': "inUserId" },
{ 'data': "dtCreationTime" },
{ 'data': "stLog" },
{ 'data': "stInstance" },
],
"language": {
"emptyTable": "There are no records at present.",
"zeroRecords": "There were no matching records found."
},
processing: true,
serverSide: false,
ordering: true,
paging: true,
searching: true
});
},
error: function (data) {
alert(data);
}
});

It should be the other way around e.g.:
<script type="text/javascript" src="/assets/js/datatables.min.js"></script>
<script type="text/javascript" >
$(document).ready(function () {
$('#mytable').DataTable({
processing: true,
serverSide: true,
ajax: {
type: "POST",
contentType: "application/json; charset=utf-8",
url: "/DataTables.aspx/Data",
data: function (d) {
return JSON.stringify({ parameters: d });
}
}
});
});
</script>

Related

Select2: Searching not working with external json file

0.13) to load a json with country names.
I can show and select the data correctly, but the searching is not working.
Everytime I type something it always returns all the values and not the ones I'm searching for.
This is my code:
$("#reg_afi_nac").select2({
width: '100%',
placeholder: 'Ingrese la nacionalidad',
language: 'es',
ajax: {
url: "<?php echo base_url('assets/json/nacionalidades.json') ?>",
dataType: "json",
type: "POST",
data: function(params) {
return {
q: params.term, // search term
};
},
processResults: function(data) {
return {
results: $.map(data, function(item) {
return {
text: item.text,
id: item.text
}
})
};
},
cache: true,
},
});

How to bind JSON data from ajax call to DataSource of pivot table webdatarocks

Here the data is not binding in the following code:
var pivot = new WebDataRocks({
container: "#wdr-component",
toolbar: true,
height: 395,
report: {
dataSource: {
dataSourceType: "json",
data: getData()
},
"slice": {
"rows": [
{
"uniqueName": "RLI_RAV_GRP_DES"
}
],
"columns": [
{
"uniqueName": "LEVEL1"
},
{
"uniqueName": "LEVEL2"
}
],
"measures": [
{
"uniqueName": "Q1",
"aggregation": "sum"
},
{
"uniqueName": "Q2",
"aggregation": "sum"
},
{
"uniqueName": "Q3",
"aggregation": "sum"
},
{
"uniqueName": "Q4",
"aggregation": "sum"
}
]
},
options:
{
grid: {
title: "Sales Report"
}
}
}
});
function getData() {
$.ajax({
type: "GET",
url: "NACGSample.aspx/GetPivotReportList",
contentType: "application/json; charset=utf-8",
dataType: 'json',
success: function (msg) {
return JSON.parse(msg.d);
//return msg.d;
},
error: function (msg) { return alert(msg); }
});
}
The issue is that you can not return a value from an asynchronous call (AJAX request).
The solution is to call a function inside your success: callback that passes the data when it is available.
Please check the following CodePen: https://codepen.io/webdatarocks/pen/eYErgGL?editors=1010

My API PUT will not work

I cannot get ajax to do a 'PUT' operation.
$('.thetest').click(function() {
console.log("Script executed");
$.ajax({
url: 'redacted for obvious reasons',
contentType: 'application/json',
success: function(result) {
alert("success?");
},
type: 'PUT',
data: {
"userId": "also redacted",
"data": {
"userSettings": {
"notificationSettings": {
"Marketing": false,
"Newsletters": true
}
}
}
},
});
});
<button class="thetest"> PRESS ME</button>
Once the button is pressed, the console.log does trigger. So I know the script is being used, it just doesn't send to the API.
Any ideas?
change type to method
$('.thetest').click(function () {
console.log("Script executed");
$.ajax({
url: 'redacted for obvious reasons',
contentType: 'application/json',
success: function (result) {
alert("success?");
},
method: 'PUT',
data: {
"userId": "also redacted",
"data": {
"userSettings": {
"notificationSettings": {
"Marketing": false,
"Newsletters": true
}
}
}
},
});
});

Reload page js after database query in MVC

I have such script:
$(document).ready(function () {
$('#requestTable').DataTable(
{
aoColumns: [
{ mDataProp: "DateStart", sTitle: "Date Start" },
{ mDataProp: "DateEnd", sTitle: "Date End" },
{ mDataProp: "Approved", sTitle: "Approved" },
{ mDataProp: "Data", sTitle: "Employee" },
{ mDataProp: "Position", sTitle: "Position" },
{ mDataProp: "", sTitle: "" }
],
columnDefs: [{
targets: 'no-sort',
orderable: false
}]
});
$('button.accept-button').click(function () {
var id = $(this).attr('data-id')
$.ajax({
type: "POST",
url: "/TableRequest/AcceptRequest",
data: { 'id': id },
success: function (msg) {
}
});
location.reload(true);
});
var tempId;
$('button.decline-button').click(function () {
tempId = $(this).attr('data-id')
$("#dialog").dialog()
});
$('button.ok-request').click(function () {
var message = $('textarea#commentForDecline').val();
$.ajax({
type: "POST",
url: "/TableRequest/DeclineRequest",
data: { 'message': message, 'id': tempId },
success: function (msg) {
}
});
$("#dialog").dialog('close');
$('textarea#commentForDecline').val('');
location.reload(true);
});
});
As you can see I reload page after post Ajax query. But is there any way to check changes in Db and refresh page after this (call the Action)? So Db changes is late and I wanna to check it.
You can reload the page after success, and from backend action return the data you want to check and after you can reload
success: function (data) {
console.log(data);
if (data.somekey === "somevalue"){
location.reload(true);
} else {
//don't reload show me some erros
}
}

Kendo Grid how to datasource update,create,delete

For some reasons I cannot use MVC-wrapper of Kendo grid. So I am trying to build Kendo grid on JavaScript.
There are 2 main problems when trying to update or create records on grid.
1-)All operations(destroy,update,create) on grid just go to create action by Datasource's of Kendo grid. For example after update a record, datasource send data to this URL to many times(number of columns):
http://localhost:63186/Administrator/DefinitionDetailCreate. It should pass values to:
http://localhost:63186/Administrator/DefinitionDetailUpdate
2-)After operation(update or create) Grid sends all data to Action Method instead of new or updated data. So it sends requests the number of columns on grid
JavaScript:
var dataItem = this.dataItem($(e.target).closest("tr"));
var code = dataItem.CODE;
// alert(code);
var crudServiceBaseUrl = "/Administrator/",
dataSource = new kendo.data.DataSource({
transport: {
read: {
url: '#Url.Action("DefinitionDetailRead", "Administrator")',
data: {DefinitionCode: code},
dataType: "json"
},
update: {
url: '#Url.Action("DefinitionDetailUpdate", "Administrator")',
type: "POST",
dataType: "text"
},
destroy: {
url: '#Url.Action("DefinitionDetailDelete", "Administrator")',
type: "POST",
dataType: "text",
},
create: {
url: '#Url.Action("DefinitionDetailCreate", "Administrator")',
type: "POST",
dataType: "text",
}
},
// batch: true,
pageSize: 9,
schema: {
data: "Data",
model: {
ID: "ID",
fields: {
ID: {editable: false, nullable: true},
DESCRIPTION: {validation: {required: true}}
}
}
}
});
$("#detailsGrid").kendoGrid({
dataSource: dataSource,
attributes: {style: "padding-left: 0px; font-size: 14px"},
pageable: {refresh: false, pageSizes: false, buttonCount: 5},
toolbar: ["create"],
columns: [
{field: "DESCRIPTION", title: "DESCRIPTION", width: "200px"},
{command: ["edit", "destroy"], title: "Operasyon", width: "100px"}],
editable: "popup"
});
Controller:
[HttpPost]
public ActionResult DefinitionDetailUpdate(Guid ID,Guid REFERENCEID,string DESCRIPTION)
{
return null;
}
[HttpPost]
public ActionResult DefinitionDetailCreate(Guid ID, Guid REFERENCEID, string DESCRIPTION)
{
return null;
}
First you might need to add parameterMap, this will help identify server side methods:
parameterMap: function (options, operation) {
var out = null;
switch (operation) {
case "create":
out = '{ "param":' + options.somevalue + '}';
break;
case "read":
out = '{ "id":' + options.somevalue + '}';
break;
case "update":
out = '{ "id":' + options.somevalue + '}';
break;
case "destroy":
out = '{ "id": ' + options.somevalue + '}';
break;
}
return out;
}
I would also suggest to keep all the dataTypes as dataType: "json"
Also you seem to be missing contentType in your transports definitions :
update: {
url: _op.serviceBaseUrl + "Update",
dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8",
complete: function (jqXhr, textStatus) {
}
},
i have posted answer for the same type of question, you may have a check
or
you may Use this code
js
var dataItem = this.dataItem($(e.target).closest("tr"));
var code = dataItem.CODE;
// alert(code);
var crudServiceBaseUrl = "/Administrator/",
dataSource = new kendo.data.DataSource({
transport: {
read: {
url: '#Url.Action("DefinitionDetailRead", "Administrator")',
type: "POST",
dataType: "json"
},
update: {
url: '#Url.Action("DefinitionDetailUpdate", "Administrator")' ,
type: "POST",
dataType: "json"
},
destroy: {
url: '#Url.Action("DefinitionDetailDelete", "Administrator")',
type: "POST",
dataType: "json",
},
create: {
url: '#Url.Action("DefinitionDetailCreate", "Administrator")',
type: "POST",
dataType: "json",
},
parameterMap: function (options, operation) {
if (operation !== "read" && options.models) {
return { models: kendo.stringify(options.models) };
}
} },
// batch: true,
pageSize: 9,
schema: {
data: "Data",
model: {
ID: "ID",
fields: {
ID: { editable: false, nullable: true },
DESCRIPTION: { validation: { required: true } }
}
}
}
});
$("#detailsGrid").kendoGrid({
dataSource: dataSource,
attributes: { style: "padding-left: 0px; font-size: 14px"},
pageable: {refresh: false, pageSizes: false, buttonCount: 5},
toolbar: ["create"],
columns: [
{field: "DESCRIPTION", title: "DESCRIPTION", width: "200px"},
{ command: ["edit", "destroy"], title: "Operasyon", width: "100px" }],
editable: "popup"
});
Controller
[HttpPost]
public ActionResult DefinitionDetailUpdate(string models)
{
//Deserialize to object
IList<UrObjectType> objName= new JavaScriptSerializer().Deserialize<IList<UrObjectType>>(models);
return Json(objName)
}
[HttpPost]
public ActionResult DefinitionDetailCreate(string models)
{
//Deserialize to object
IList<UrObjectType> objName= new JavaScriptSerializer().Deserialize<IList<UrObjectType>>(models);
return Json(objName)
}
Note that parameterMap: function() send updated data in serialize string format with name models so you should use "models" as parameter name in your action
i hope this will help you:)

Categories