csrf token set as post parameter while deleting action in Jtable (Jquery ) - javascript

Hi i'm trying to add csrf token in post while deleting record in jtable its not working but listAction & updateAction is working fine.
My Code snippets :-
$(document).ready(function () {
$('#main-content').jtable({
title: ' Data',
selecting: true, //Enable selecting
multiselect: true, //Allow multiple selecting
selectingCheckboxes: true, //Show checkboxes on first column
paging: true, //Enable paging
pageSize: 10, //Set page size (default: 10)
actions: {
listAction:"${pageContext.request.contextPath}/mycontroller/all" ,
// createAction:"${pageContext.request.contextPath}/mycontroller/create",
updateAction:"${pageContext.request.contextPath}/mycontroller/edit",
deleteAction:"${pageContext.request.contextPath}/mycontroller/delete"
},
fields: {
code: {
title:'Code',
width: '25%',
key: true,
edit:true,
input: function (data) {
if (data.value) {
return '<input type="text" readonly class="jtable-input-readonly" name="code" value="' + data.value + '"/>';
}
},
},
name: {
title: 'Name',
width: '25%',
create:true,
edit:true
},
craetedTs: {
title: 'Created',
width: '25%',
edit:false
},
modifiedTs: {
title: 'mdate',
width: '25%',
edit:true,
input: function (data) {
if (data.value) {
mdate='';
var date = new Date();
var options = {
year: "numeric", month: "2-digit",
day: "2-digit", hour: "2-digit", minute: "2-digit" ,second:"2-digit"
};
today=date.toLocaleTimeString("en-us", options);
today=today.replace(',', '');
return '<input type="text" readonly class="jtable-input-readonly" name="modifiedTs" value="' + today + '"/>';
}
}
},
_csrf: {
visibility: 'hidden',
edit:true,
input: function (data) {
return '<input type="hidden" name="${_csrf.parameterName}" value="${_csrf.token}" />';
}
}
}
});
$('#main-content').jtable('load',{'${_csrf.parameterName}' : '${_csrf.token}'});
//Delete selected
$('#DeactiveID').button().click(function () {
var $selectedRows = $('#main-content').jtable('selectedRows');
$('#main-content').jtable('deleteRows', $selectedRows);
});
});
Even i tried for deleting code bellow:-
deleteAction: function (postData) {
return $.Deferred(function ($dfd) {
$.ajax({
url: '/Demo/DeleteStudent',
type: 'POST',
dataType: 'json',
data: '${_csrf.parameterName}' + "=" +'${_csrf.token}' ,
success: function (data) {
$dfd.resolve(data);
},
error: function () {
$dfd.reject();
}
});
});
}
But when i checked delete action url the entire method was reflecting

Add meta elements to the page you are invoking the ajax method from
<meta name="_csrf" content="${_csrf.token}"/>
<meta name="_csrf_header" content="${_csrf.headerName}"/>
And make this change to your deleteAction
deleteAction: function (postData) {
return $.Deferred(function ($dfd) {
var token = $("meta[name='_csrf']").attr("content");
var header = $("meta[name='_csrf_header']").attr("content");
$.ajax({
url: '/Demo/DeleteStudent',
type: 'POST',
dataType: 'json',
beforeSend: function (request)
{
request.setRequestHeader(header, token);
},
success: function (data) {
$dfd.resolve(data);
},
error: function () {
$dfd.reject();
}
});
});
}

If somebody is still wondering, Lalit got me going in the right direction, but my final solution is this:
deleteAction: function (postData) {
return $.Deferred(function ($dfd) {
postData.csrf_token = csrf_token;
$.ajax({
url: 'prizes/delete',
type: 'POST',
dataType: 'json',
data: postData,
beforeSend: function (request)
{
request.setRequestHeader("csrf_token", csrf_token);
},
success: function (data) {
$dfd.resolve(data);
},
error: function () {
$dfd.reject();
}
});
});
}
This solves the issue with passing csrf, or any additional data, for that matter, in jTable AJAX delete call. As for the other cases. Putting this right after you include the jTable js foxes the initial load:
$.extend(true, $.hik.jtable.prototype.options, {
ajaxSettings: {
data: {csrf_token: csrf_token},
}
});
And then there is this hidden field to add to the field list:
csrf_token: {
visibility: 'hidden',
edit:true,
input: function (data) {
return "<input type='hidden' name='csrf_token' value='" + csrf_token + "'/>";
}
}
Here is my code as a full example:
<!-- Include jTable script file. -->
<script src="{{site.uri.public}}/jtable/jquery.jtable.js" type="text/javascript"></script>
<script type="text/javascript">
var csrf_token = $('meta[name=csrf_token]').attr("content");
$.extend(true, $.hik.jtable.prototype.options, {
ajaxSettings: {
data: {csrf_token: csrf_token},
}
});
</script>
<script type="text/javascript">
$(document).ready(function () {
var csrf_token = $('meta[name=csrf_token]').attr("content");
$("#PrizesTableContainer").jtable({
title: 'Prizes',
actions: {
listAction: 'prizes/get',
createAction: 'prizes/create',
updateAction: 'prizes/update',
deleteAction: function (postData) {
return $.Deferred(function ($dfd) {
postData.csrf_token = csrf_token;
$.ajax({
url: 'prizes/delete',
type: 'POST',
dataType: 'json',
data: postData,
beforeSend: function (request)
{
request.setRequestHeader("csrf_token", csrf_token);
},
success: function (data) {
$dfd.resolve(data);
},
error: function () {
$dfd.reject();
}
});
});
}
},
fields: {
id: {
key: true,
list: false
},
machine_name: {
title: 'Machine name',
width: '10%'
},
reel1: {
title: 'Reel1',
width: '15%'
},
reel2: {
title: 'Reel2',
width: '15%'
},
reel3: {
title: 'Reel3',
width: '15%'
},
payout_credits: {
title: 'Payout credits',
width: '15%'
},
payout_winnings: {
title: 'Payout winnings',
width: '15%'
},
probability: {
title: 'Probability',
width: '15%'
},
csrf_token: {
visibility: 'hidden',
edit:true,
input: function (data) {
return "<input type='hidden' name='csrf_token' value='" + csrf_token + "'/>";
}
}
}
});
$("#PrizesTableContainer").jtable('load');
});
</script>

Related

SUMO SELECT REFRESH ISSUE

Sumo select is not refreshing the data in it.
Action Method is return the correct List.
Just like J QUERY multi select rebuild()
function is available is there anything I am missing?
$("#ddlCountry").change(function () { BindDDlLocation(CountryId); });
function BindDDlLocation(CountryId) {
var ddlLocation = $("#ddlLocation");
$.ajax({
url: RootUrl + '/Home/BindMasterDropDown',
type: "GET",
data: { TableType: 'tbllocation', RegionId: '0', Country_id: CountryId, Categ_Id: '0', SubCateg_Id: '0', EntityID: '0', DepartmentID: '0' },
datatype: 'json',
async: false,
success: function (result) {
$("#ddlLocation").html('');
ddlLocation.append($("<option></option>").val('').html('--select--'));
$.each(result, function (key, value) {
ddlLocation.append($("<option></option>").val(value.ID).html(value.vDescription));
});
//alert("location binded");
$("#ddlLocation").SumoSelect({ csvDispCount: 1, search: true, searchText: 'Enter here.' });
$(".SumoSelect").css('margin-top', '15px');
},
error: function (err) {
alert(err.statusText);
}
});
}
This is the ANSWER: It works fine now.
REFERENCE :
https://github.com/HemantNegi/jquery.sumoselect/issues/286
//bimmy
$("#ddlLocation").SumoSelect({ csvDispCount: 1, search: true, searchText: 'Enter here.', triggerChangeCombined: false });
$("#ddlLocation").SumoSelect().sumo.reload();
$(".SumoSelect").css('margin-top', '15px');
//bimmy
Full CODE:
function BindDDlLocation(CountryId) {
var ddlLocation = $("#ddlLocation");
$.ajax({
url: RootUrl + '/Home/BindMasterDropDown',
type: "GET",
data: { TableType: 'tbllocation', RegionId: '0', Country_id: CountryId, Categ_Id: '0', SubCateg_Id: '0', EntityID: '0', DepartmentID: '0' },
datatype: 'json',
async: false,
success: function (result) {
$("#ddlLocation").html('');
ddlLocation.append($("<option></option>").val('').html('--select--'));
$.each(result, function (key, value) {
ddlLocation.append($("<option></option>").val(value.ID).html(value.vDescription));
});
//bimmy
$("#ddlLocation").SumoSelect({ csvDispCount: 1, search: true, searchText: 'Enter here.', triggerChangeCombined: false });
$("#ddlLocation").SumoSelect().sumo.reload();
$(".SumoSelect").css('margin-top', '15px');
//bimmy
},
error: function (err) {
alert(err.statusText);
}
});
}
$('.the_name_of_select_class').SumoSelect().reload();

jQuery Select2 - get maximum selectable by data attribute

this is html code of my select2 field.
<select data-init-plugin="select2" data-max="4" multiple="" id="mls" name="mls" class="select2 form-control full-width ajax-supported select2-hidden-accessible" data-callback="getAgents" tabindex="-1" aria-hidden="true"></select>
and this is the select2 JavaScript code.
$('.ajax-supported').select2({
ajax: {
dataType: 'json',
multiple: true,
type: "POST",
data: function (term) {
return {
'_token': $('#_token').val(),
name: $(this).attr('name'),
callback: $(this).data('callback'),
q: term.term,
};
},
url: '{{ url('listing-field-ajax-callback') }}',
processResults: function (data) {
return {
results: $.map(data, function (item) {
return {
text: item.itemName,
id: item.id
}
})
};
},
},
minimumInputLength: 1,
maximumSelectionLength: maximum_selectable_items, // this is where i want 4 from data attribute data-max=4
});
now i want to get data attribute data-max = 4 and i want to use it in my maximumSelectionLength and want to control the number of selected items. how can i get data attribute from the select HTML and use that in my JavaScript?
well i tried this code and it worked.
$.each($('.ajax-supported'), function(k, field) {
var max;
console.log(field);
if($(field).data('max')) {
max = parseInt($(field).data('max'));
}
else {
max = 1;
}
$(field).select2({
ajax: {
dataType: 'json',
multiple: true,
type: "POST",
data: function (term) {
return {
'_token': $('#_token').val(),
name: $(field).attr('name'),
callback: $(field).data('callback'),
q: term.term,
};
},
url: '{{ url('listing-field-ajax-callback') }}',
processResults: function (data) {
return {
results: $.map(data, function (item) {
return {
text: item.itemName,
id: item.id
}
})
};
},
},
minimumInputLength: 1,
maximumSelectionLength: max,
});
});

How to remove all items from a kendoListBox

I have two kendo list boxes they exchange items between them. Basically an Items available and an Items selected pair.
I have Json service which controls what items are available via a Json array.
When the user selects a new filter I want both Kendo List Boxes to clear the items out before adding the new items from the server.
Currently it appends the new list from the server to the current list.
$(document).ready(function () {
$("#filterKeyWord").click(function () {
getResults($("#keywords"));
});
$("#availableReports").kendoListBox({
dataTextField: "Name",
dataValueField: "ID",
connectWith: "selectedReports",
dropSources: ["availableReports"],
toolbar: {
tools: ["transferTo", "transferFrom", "transferAllTo", "transferAllFrom", "remove"]
}
});
$("#selectedReports").kendoListBox({
dataTextField: "Name",
dataValueField: "ID",
dropSources: ["selectedReports"],
remove: function (e) {
setSelected(e, false);
},
add: function (e) {
setSelected(e, true);
}
});
var mydata = { ReportName: "", UserId: "" };
mydata.ReportName = "SomeName";
mydata.UserId = "SomeUser";
var crudService = "",
dataSource = new kendo.data.DataSource({
serverFiltering: true,
transport: {
read: {
url: crudService + "GetReportList",
dataType: "json",
type: "get",
contentType: "application/json; charset=utf-8",
},
update: {
url: crudService + "SaveReportList2",
dataType: "json",
contentType: "application/json; charset=utf-8",
type: "post",
},
filter: {
url: crudService + "GetReportList",
dataType: "json",
type: "get",
contentType: "application/json; charset=utf-8",
},
parameterMap: function (options, operation) {
console.log(operation);
if (operation !== "read" && options.models) {
return JSON.stringify({ models: options.models });
}
if (operation === "read") {
return "request=" + JSON.stringify(mydata);
}
}
},
batch: true,
requestStart: function () {
kendo.ui.progress($(".demo-section"), true);
console.log("request start");
},
requestEnd: function () {
kendo.ui.progress($(".demo-section"), false);
console.log("request end");
},
error: function (e) {
console.log("Error" + e);
},
change: function (e) {
console.log("change" + this.data.length);
setDropDownBoxes(this);
},
schema: {
model: {
id: "ID",
fields: {
ID: { type: "number" },
Selected: { type: "boolean" },
Name: { type: "string" },
Description: { type: "string" },
InternalId: { type: "string" }
}
}
}
});
$("#saveReportList").kendoButton({
click: function (e) {
dataSource.sync();
}
});
$("#getReportList").kendoButton({
click: function (e) {
mydata.ReportName = $("#keywords").val();
dataSource.read();
}
});
function setDropDownBoxes(obj) {
var data = obj.data();
var availableReports = $("#availableReports").data("kendoListBox");
var selectedReports = $("#selectedReports").data("kendoListBox");
var items = availableReports.dataItems();
for (var i = 0; i < data.length; i++) {
if (data[i].Selected) {
selectedReports.add(data[i]);
}
else {
availableReports.add(data[i]);
}
}
}
function setSelected(e, flag) {
var removedItems = e.dataItems;
for (var i = 0; i < removedItems.length; i++) {
console.log(flag + " " + removedItems[i].ID + " " + removedItems[i].Name + " " + removedItems[i].Selected);
var item = dataSource.get(removedItems[i].ID);
item.Selected = flag;
item.dirty = !item.dirty;
}
}
});
Not sure where in your exactly the clening should be performed, but, you can use both remove() and item() methods togheter to clear a listBox.
remove() method accepts a list of li elements, which is what items() returns, so it will remove the whole li collection from the list.
var listBox = $("#listBox").data("kendoListBox");
listBox.remove(listBox.items());
Demo

Create ui-grid with async call

I am trying to create a ui-grid with some DDL filter (from get data). If I try with async: false, all works perfectly. This is the call:
var Documents = [];
var solutionSetColumn = {};
var solutionSetFilters = [];
LoadData = function () {
Documents = [];
$.ajax({
type: "POST", url: url,
success: function (data) {
Documents = data.d;
},
error: function (err) {
}
});
}
}
$.ajax({
type: "POST", url: url,
success: function (data) {
solutionSetColumn = { field: 'SolutionSet', displayName: 'Solution Set', width: 190, filter: { type: uiGridConstants.filter.SELECT, selectOptions: data.d } };
},
error: function (err) {
solutionSetColumn = { field: 'SolutionSet', displayName: 'Solution Set', width: 190 }
}
});
LoadData();
gridOptions = {
enableHorizontalScrollbar: 2,
enableVerticalScrollbar: 0,
enableFiltering: true,
data: Documents,
columnDefs: [
{ field: 'Name', displayName: 'Nome File', width: 200 },
solutionSetColumn
]
}
$scope.gridOptions = gridOptions;
});
How to get all async without gridOption error like colDef undefined? Obviously without the setTimeout! Thanks
You need to move your $scope.gridOptions (and the options definition) into the success path of your ajax call.

How to initialize a select2 disabled

I have a simple select2 init which I want to be disabled by default without chaining a .select2("enable", false) afterwards.
HTML:
<input type='hidden' value="192" data-init-text='Bla bla' name="input" id="test" style="width:300px;" />
JS:
$(document).ready(function() {
$('#test').select2({
minimumInputLength: 3,
placeholder: "Search",
enable: "false", // I want this to be working!
ajax: {
url: "http://www.weighttraining.com/sm/search",
dataType: 'jsonp',
quietMillis: 100,
data: function(term, page) {
return {
types: ["exercise"],
limit: -1,
term: term
};
},
results: function(data, page ) {
return { results: data.results.exercise }
}
},
formatResult: function(exercise) {
return "<div class='select2-user-result'>" + exercise.term + "</div>";
},
formatSelection: function(exercise) {
return exercise.term;
},
initSelection : function (element, callback) {
var elementText = $(element).attr('data-init-text');
callback({"term":elementText});
}
});
});
See my JSFiddle for an example. Select2 Docs here.
Simply add the disabledattribute to your input.
<input disabled type='hidden' value="192" data-init-text='Bla bla' name="input" id="test" style="width:300px;" />
$(document).ready(function() {
$('#test').select2({
minimumInputLength: 3,
placeholder: "Search",
ajax: {
url: "http://www.weighttraining.com/sm/search",
dataType: 'jsonp',
quietMillis: 100,
data: function(term, page) {
return {
types: ["exercise"],
limit: -1,
term: term
};
},
results: function(data, page ) {
return { results: data.results.exercise }
}
},
formatResult: function(exercise) {
return "<div class='select2-user-result'>" + exercise.term + "</div>";
},
formatSelection: function(exercise) {
return exercise.term;
},
initSelection : function (element, callback) {
var elementText = $(element).attr('data-init-text');
callback({"term":elementText});
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/3.2.0/select2.min.js"></script>
<input disabled type='hidden' value="192" data-init-text='Bla bla' name="input" id="test" style="width:300px;" />
Try this:
Fiddle
$(document).ready(function() {
$('#test').select2({
minimumInputLength: 3,
placeholder: "Search",
ajax: {
url: "http://www.weighttraining.com/sm/search",
dataType: 'jsonp',
quietMillis: 100,
data: function(term, page) {
return {
types: ["exercise"],
limit: -1,
term: term
};
},
results: function(data, page ) {
return { results: data.results.exercise }
}
},
formatResult: function(exercise) {
return "<div class='select2-user-result'>" + exercise.term + "</div>";
},
formatSelection: function(exercise) {
return exercise.term;
},
initSelection : function (element, callback) {
var elementText = $(element).attr('data-init-text');
callback({"term":elementText});
}
}).select2("enable", false);
});
I am including the latest working code below:
$("your-selector").select2({
// configuration params
}).prop("disabled", true);
Notice the prop method. Pretty simple, right?

Categories