Kendo Grid Binding with Razor - javascript

I setup a function used to save the grid's state along with its options to a database whenever something is modified. Every user will have their own respective settings.
The saving and loading functions of the grip options are functional, however upon page loading, the loadGridState function is called and so is the saveGridState although no change has been made to the grid by the user yet.
I would like to learn about a better way to perform the binding with the grid upon loading without having to mix the save functions with the databound event functions from Kendo.
This is the code within a JavaScript section:
$(function () {
$("#navHistory").addClass("navMenuSelected");
$("#navHistory > a").css("color", "black");
var grid = $("#HistoricGrid").data("kendoGrid");
var gridstate = kendo.stringify(grid.getOptions());
grid.bind("dataBound", onDataBound);
grid.bind("columnResize", onColumnResize);
LoadGridState();
$('#search').click(function (e) {
e.preventDefault();
$('#excelButton').prop('disabled', true);
$('#pdfButton').prop('disabled', true);
$('search').prop('disabled', true);
grid.dataSource.read();
});
$('#excelButton').click(function () {
grid.saveAsExcel();
});
$('#pdfButton').click(function () {
grid.saveAsPDF();
});
$("#save").click(function (e) {
e.preventDefault();
SaveGridState();
});
$("#load").click(function (e) {
e.preventDefault();
LoadGridState();
});
//Grid event.
function onDataBound(e) {
SaveGridState();
var excelActivation = $('#excelButton').prop('disabled');
var pdfActivation = $('#pdfButton').prop('disabled');
var searchActivation = $('#search').prop('disabled');
if (excelActivation) {
$('#excelButton').prop('disabled', false);
}
if (pdfActivation) {
$('#pdfButton').prop('disabled', false);
}
if (searchActivation) {
$('#search').prop('disabled', false);
}
}
//Grid event.
function onColumnResize(e) {
SaveGridState();
}
function SaveGridState() {
//region #Bug 1818 - New SaveGridState() function saves the Grid's State independent of the language
var gridOptions = grid.getOptions();
if (gridOptions != null &&
gridOptions.dataSource &&
gridOptions.dataSource.transport != null &&
gridOptions.dataSource.transport.read &&
gridOptions.dataSource.transport.read.url != null
) {
delete gridOptions.dataSource.transport.read.url;
}
if (gridOptions != null &&
gridOptions.groupable &&
gridOptions.groupable.messages != null &&
gridOptions.groupable.messages.empty &&
gridOptions.groupable.messages.empty != null
) {
delete gridOptions.groupable.messages.empty;
}
if (gridOptions != null &&
gridOptions.pageable &&
gridOptions.pageable.messages != null &&
gridOptions.pageable.messages.itemsPerPage &&
gridOptions.pageable.messages.itemsPerPage != null
) {
delete gridOptions.pageable.messages.itemsPerPage;
}
$(gridOptions.columns).each(function () {
$(this).removeProp("title");
});
var gridColumns = kendo.stringify(gridOptions);
console.log(gridOptions);
$.ajax({
url: '#Url.Action("GridSaveOption", "Global")',
type: 'POST',
async: false,
data: { gridName: "HistoricGrid", gridOption: gridColumns },
success: function (result, status) { },
error: function (result, status) {
console.log('Error on SaveGrid.');
}
});
//end region #Bug 1818
}
function LoadGridState() {
$.ajax({
url: '#Url.Action("GridLoadOption", "Global")',
type: 'POST',
async: false,
data: { gridName: "HistoricGrid" },
datatype: 'text',
success: function (result, status) {
//region #Bug 1822 - Adjust the titles of the Grid to the current language
//If there is a corresponding data grid option for current user
if (result) {
var gridOptions = JSON.parse(result);
if (gridOptions != null &&
gridOptions.dataSource &&
gridOptions.dataSource.transport != null &&
gridOptions.dataSource.transport.read &&
gridOptions.dataSource.transport.read.url != null
) {
delete gridOptions.dataSource.transport.read.url;
}
if (gridOptions != null &&
gridOptions.groupable &&
gridOptions.groupable.messages != null &&
gridOptions.groupable.messages.empty &&
gridOptions.groupable.messages.empty != null
) {
delete gridOptions.groupable.messages.empty;
}
if (gridOptions != null &&
gridOptions.pageable &&
gridOptions.pageable.messages != null &&
gridOptions.pageable.messages.itemsPerPage &&
gridOptions.pageable.messages.itemsPerPage != null
) {
delete gridOptions.pageable.messages.itemsPerPage;
}
if (gridOptions != null &&
gridOptions.pdf
) {
delete gridOptions.pdf;
}
if (gridOptions != null &&
gridOptions.columns
) {
delete gridOptions.columns;
}
grid.setOptions(gridOptions);
//end region #Bug 1822
}
//If there is no data grid option for current user, use default
else {
//#Bug 1866 - In case the user has no style defined, it will order by creation date by default
var dsSort = [];
dsSort.push({ field: "CreationDate", dir: "desc" });
grid.dataSource.sort(dsSort);
}
},
error: function (result, status) {
console.log('Error on LoadGrid.');
}
});
}
});

Related

Add Ajax Add To Cart Button to Front Page

I'm trying to add ajax to add to cart button on front page.
The setup is using Divi. Divi's woo product module does not display Add-to-cart button. I use the below to display add-to-cart button on front page. That works but the only issue is the Ajax is not working on front page. I've enabled "Enable AJAX add to basket buttons on archives" from Woocommerce settings.
add_action('template_redirect', 'work_only_on_front_page', 10);
function work_only_on_front_page(){
if ( is_front_page() ) {
add_action('woocommerce_after_shop_loop_item_title', 'woocommerce_template_loop_add_to_cart', 10);
}
}
Below works well on other pages other than the front page.
(function ($) {
$(document).on('click', '.single_add_to_cart_button', function (e) {
e.preventDefault();
var $thisbutton = $(this),
$form = $thisbutton.closest('form.cart'),
id = $thisbutton.val(),
product_qty = $form.find('input[name=quantity]').val() || 1,
product_id = $form.find('input[name=product_id]').val() || id,
variation_id = $form.find('input[name=variation_id]').val() || 0;
var data = {
action: 'woocommerce_ajax_add_to_cart',
product_id: product_id,
product_sku: '',
quantity: product_qty,
variation_id: variation_id,
};
$(document.body).trigger('adding_to_cart', [$thisbutton, data]);
$.ajax({
type: 'post',
url: wc_add_to_cart_params.ajax_url,
data: data,
beforeSend: function (response) {
$thisbutton.removeClass('added').addClass('loading');
},
complete: function (response) {
$thisbutton.addClass('added').removeClass('loading');
},
success: function (response) {
if (response.error && response.product_url) {
window.location = response.product_url;
return;
} else {
$(document.body).trigger('added_to_cart', [response.fragments, response.cart_hash, $thisbutton]);
}
},
});
return false;
});
})(jQuery);
function woocommerce_ajax_add_to_cart_js() {
if (is_product() || is_product_category() || is_shop() || is_front_page()) {
wp_enqueue_script('woocommerce-ajax-add-to-cart', get_stylesheet_directory_uri() . '/assets/js/ajax-add-to-cart.js', array('jquery'), '', true);
}
}
add_action('wp_enqueue_scripts', 'woocommerce_ajax_add_to_cart_js', 99);
add_action('wp_ajax_woocommerce_ajax_add_to_cart', 'woocommerce_ajax_add_to_cart');
add_action('wp_ajax_nopriv_woocommerce_ajax_add_to_cart', 'woocommerce_ajax_add_to_cart');
function woocommerce_ajax_add_to_cart() {
$product_id = apply_filters('woocommerce_add_to_cart_product_id', absint($_POST['product_id']));
$quantity = empty($_POST['quantity']) ? 1 : wc_stock_amount($_POST['quantity']);
$variation_id = absint($_POST['variation_id']);
$passed_validation = apply_filters('woocommerce_add_to_cart_validation', true, $product_id, $quantity);
$product_status = get_post_status($product_id);
if ($passed_validation && WC()->cart->add_to_cart($product_id, $quantity, $variation_id) && 'publish' === $product_status) {
do_action('woocommerce_ajax_added_to_cart', $product_id);
if ('yes' === get_option('woocommerce_cart_redirect_after_add')) {
wc_add_to_cart_message(array($product_id => $quantity), true);
}
WC_AJAX :: get_refreshed_fragments();
} else {
$data = array(
'error' => true,
'product_url' => apply_filters('woocommerce_cart_redirect_after_error', get_permalink($product_id), $product_id));
echo wp_send_json($data);
}
wp_die();
}
Another thing to check is to ensure that the function woocommerce_ajax_add_to_cart_js() is being called and the script is being enqueued on the front page.
You can check the browser's console to see if there are any errors related to the Javascript code not being loaded.

Call every element one by one

I have 3 paragraphs here. The problem is that they are displaying at the same time.
What I wanted is they will auto show and then hide one at a time.
Scenario:
First paragraph // show then hide
Sec paragraph // next show then hide
Third paragraph // next show then hide
if(p_name != "" && l_name != "" && t_name !="")
{
session.rpc('/custom/custom',
{
p_name: p_name,
}).then(function ()
{
$("p.one").addClass("show").hide(5000);
});
session.rpc('/cus/cus',
{
l_name : l_name,
}).then(function ()
{
$("p.two").addClass("show").hide(5000);
});
session.rpc('/cuz/cuz',
{
t_name : t_name,
}).then(function ()
{
$("p.three").addClass("show").hide(5000);
});
}
maybe this is what you are looking for
if (p_name != "" && l_name != "" && t_name != "") {
session.rpc('/custom/custom', {
p_name: p_name,
}).then(function() {
$("p.one").addClass("show").hide(5000);
session.rpc('/cus/cus', {
l_name: l_name,
}).then(function() {
$("p.two").addClass("show").hide(5000);
session.rpc('/cuz/cuz', {
t_name: t_name,
}).then(function() {
$("p.three").addClass("show").hide(5000);
});
});
});
}

Javascript promise issue

I am uploading an image using drag n drop and cropping it using croppie plugin. Also, in case if the user has selected the wrong image and wants to change it then there is a browse again button to switch back to drag n drop state.
Everything was working fine while I was doing this with jquery code. However, I am trying to refactor my code to use Javascript Promise, it just runs for the first time only.
Promise code:
const dragDrop = (params, element) => {
return new Promise((resolve, reject) => {
$(element || '.drag-drop').on('dragover', (e) => {
e.preventDefault();
}).on('dragleave', (e) => {
e.preventDefault();
}).on('drop', (e) => {
e.preventDefault();
let fileList = e.originalEvent.dataTransfer.files;
let conditions = $.extend({}, {
files: 1,
fileSize: (1024 * 1024 * 5),
type: ["image/gif", "image/jpeg", "image/jpg", "image/png"],
extension: ["gif", "jpeg", "jpg", "png"]
}, (params || {}));
if (fileList.length > conditions.files)
{
reject('Please choose only ' + conditions.files + ' file(s)');
}
else if (fileList[0].size > (conditions.fileSize))
{
reject('File to large.!<br>Allowed: ' + (conditions.fileSize) + 'MB');
}
else
{
if (fileList[0].type == '')
{
let ext = (fileList[0].name).split('.');
if ($.inArray(ext[ext.length - 1], conditions.extension) < 0)
{
reject('File type not allowed');
}
}
else if ($.inArray(fileList[0].type, conditions.type) < 0)
{
reject('File type not allowed');
}
}
resolve(fileList);
});
})
};
Drag-Drop code:
dragDrop().then((files) => {
croppie({
url: 'url to upload',
data: {
token: "user identification token string"
}
}, files);
}).catch((message) => {
alert(message);
});
Croppie code:
function croppie(ajax, files, croppie, el)
{
// variables
let $image = $((el.image !== undefined) ? el.image : 'div.js-image');
let $button = $((el.button !== undefined) ? el.button : '.js-crop-button');
let $dragDrop = $((el.dragDrop !== undefined) ? el.dragDrop : '.drag-drop');
let $browseButton = $((el.browse !== undefined) ? el.browse : '.js-browse');
$imageCrop = $image.croppie($.extend(true, {
enableExif: true,
enableOrientation: true,
viewport: {
width: 200,
height: 200,
type: 'square'
},
boundary: {
height: 500
}
}, croppie)).removeClass('d-none');
var reader = new FileReader();
reader.onload = (event) => {
$imageCrop.croppie('bind', {
url: event.target.result
});
}
reader.readAsDataURL(files[0]);
$image.parent().removeClass('d-none');
$button.removeClass('d-none');
$dragDrop.addClass('d-none');
$('.js-rotate-left, .js-rotate-right').off('click').on('click', function (ev) {
$imageCrop.croppie('rotate', parseInt($(this).data('deg')));
});
$browseButton.off('click').on('click', function() {
$image.croppie('destroy');
$image.parent().addClass('d-none');
$button.addClass('d-none');
$dragDrop.removeClass('d-none');
});
$button.off('click').on('click', () => {
$imageCrop.croppie('result', {
type: 'canvas',
size: 'viewport'
}).then((response) => {
ajaxRequest($.extend(true, {
data: {
"image": response,
},
success: (data) => {
(data.success == true)
? window.parent.location.reload()
: alert(data.message);
}
}, ajax));
});
});
}

kendo grid inline edit dropdown will not expand on tab navigation

I'm having an issue with Kendo Grid in Angular where the custom drop down I've implemented will not open when tab navigating to that column. The built in text and number editor fields are editable on tab navigation but my custom drop down will not expand. I have to click on it to get the drop down effect.
My goal here is to allow the user to log an an entire row of data without having to take their hands off the keyboard.
My column is defined like so:
gridColumns.push({
field: currentField.FieldName.replace(/ /g, "_"),
title: currentField.FieldName,
editor: $scope.dropDownAttEditor,
template: function (dataItem) {
return $scope.dropDownTemplate(dataItem, currentField.FieldName);
}
});
My gridOptions are defined as follows:
$scope.gridOptions = {
dataSource: new kendo.data.DataSource({
transport: {
read: {
url: appconfig.basePath + '/api/DrillHoleManager/DrillHoleInterval',
type: 'POST',
contentType: 'application/json'
},
update: {
url: appconfig.basePath + '/api/DrillHoleManager/DrillHoleIntervalUpdate',
type: 'POST',
contentType: 'application/json'
},
parameterMap: function (data, operation) {
if (operation === "read") {
data.DrillHoleId = $scope.entity.Id;
data.DrillHoleIntervalTypeId = $stateParams.ddhinttypeid;
// convert the parameters to a json object
return kendo.stringify(data);
}
if (operation === 'update') {
// build DrillHoleIntervalDto object with all ATT/CMT values to send back to server
var drillHoleInterval = { Id: data.Id, Name: data.Name, From: data.From, To: data.To };
drillHoleInterval.Attributes = [];
drillHoleInterval.Comments = [];
var attributeFields = $.grep($scope.currentFields, function (e) { return e.DrillHoleTabFieldType == DrillHoleTabFieldTypeEnum.IntervalAttribute });
$.each(attributeFields, function (idx, attributeField) {
drillHoleInterval.Attributes.push({
Id: attributeField.AttributeDto.Id,
LookupId: data[attributeField.FieldName.replace(/ /g, "_")]
});
});
var commentFields = $.grep($scope.currentFields, function (e) { return e.DrillHoleTabFieldType == DrillHoleTabFieldTypeEnum.IntervalComment });
$.each(commentFields, function (idx, commentField) {
drillHoleInterval.Comments.push({
Id: commentField.CommentDto.Id,
Value: ((data[commentField.FieldName.replace(/ /g, "_")] != "") ? data[commentField.FieldName.replace(/ /g, "_")] : null)
});
});
return kendo.stringify(drillHoleInterval);
}
// ALWAYS return options
return options;
}
},
schema: { model: { id : "Id" }},
serverPaging: false,
serverSorting: false,
serverFiltering: false
//,autoSync: true
}),
columns: gridColumns,
dataBound: onDataBound,
autoBind: false,
navigatable: true,
scrollable: false,
editable: true,
selectable: true,
edit: function (e) {
var grid = $("#ddhintgrid").data("kendoGrid");
//grid.clearSelection();
grid.select().removeClass('k-state-selected');
// select the row currently being edited
$('[data-uid=' + e.model.uid + ']').addClass('k-state-selected');
e.container[0].focus();
}
};
Here is a custom event to handle the 'Tab' keypress. The point of this is I want a new record automatically added to the grid if the user presses 'Tab' at the end of the last line:
$("#ddhintgrid").keydown(function (e) {
if (e.key == "Tab") {
var grid = $("#ddhintgrid").data("kendoGrid");
var data = grid.dataSource.data();
var selectedItem = grid.dataItem(grid.select());
var selectedIndex = null
if (selectedItem != null) {
selectedIndex = grid.select()[0].sectionRowIndex;
if (selectedIndex == data.length - 1) { // if the bottom record is selected
// We need to manually add a new record here so that the new row will automatically gain focus.
// Using $scope.addRecord() here will add the new row but cause the grid to lose focus.
var newRecord = { From: grid.dataSource.data()[selectedIndex].To };
var currentCmtFields = $.grep($scope.currentFields, function (e) { return e.DrillHoleTabFieldType == DrillHoleTabFieldTypeEnum.IntervalComment; });
$.each(currentCmtFields, function (idx, currentCmtField) {
newRecord[currentCmtField.FieldName.replace(/ /g, "_")] = null;
});
grid.dataSource.insert(data.length, newRecord);
// edit the new row
grid.editRow($("#ddhintgrid tr:eq(" + (data.length) + ")"));
}
}
}
});
Here is my template for the drop down column:
$scope.dropDownTemplate = function (dataItem, fieldName) {
var currentLookups = $.grep($scope.currentFields, function (e) { return e.FieldName == fieldName; })[0].AttributeDto.Lookups;
var selectedLookup = $.grep(currentLookups, function (e) { return e.Id == dataItem[fieldName.replace(/ /g, "_")]; })[0];
// With the custom dropdown editor when going from null to a value the entire lookup object (id, name) is placed in the
// dataItem[field_name] instead of just the id. We need to replace this object with just the id value and return the name of
// the lookup to the template.
if (typeof selectedLookup == 'undefined' && dataItem[fieldName.replace(/ /g, "_")] != null) {
selectedLookup = angular.copy(dataItem[fieldName.replace(/ /g, "_")]);
dataItem[fieldName.replace(/ /g, "_")] = selectedLookup.Id;
}
if (selectedLookup != null && selectedLookup != '') {
return selectedLookup.Name;
}
else {
return '';
}
};
And finally here is the custom editor for the drop down column:
$scope.dropDownAttEditor = function (container, options) {
var editor = $('<input k-data-text-field="\'Name\'" k-data-value-field="\'Id\'" k-data-source="ddlDataSource" data-bind="value:' + options.field + '"/>')
.appendTo(container).kendoDropDownList({
dataSource: $.grep($scope.currentFields, function (e) { return e.FieldName == options.field.replace(/_/g, ' '); })[0].AttributeDto.Lookups,
dataTextField: "Name",
dataValueField: "Id"
});
};
I know this is a lot to take in but if you have any questions just let me know.
My ultimate goal is that I want the user to be able to navigate the grid using the 'Tab' key and edit every field without having to use the mouse.

JQuery popup $.post inner function do not working

Please help me in my Javascript - $.post - popup script. I tried to debug the script below, but I found that it doesn't go inside the function(data)... What can be the problem? Thanks for replies.
Here is my code:
$(function () {
$('#survey').dialog({
bgiframe: true,
autoOpen: false,
modal: true,
width: 500,
resizable: false,
buttons: {
Submit: function () {
if ($("input[name='elso']:checked").val() !== undefined && $("input[name='masodik']:checked").val() !== undefined && $("input[name='harmadik']:checked").val() !== undefined && $("input[name='negyedik']:checked").val() !== undefined) {
setCookie('POPsurvey', 'POPsurvey', 30);
$.post("process_survey.php", $("#popup_survey").serialize(), alert("hsgh"),
function (data) {
if (data.db_check == 'fail') {
$("#error_message").html("<p>Adatbázisunk nem elérhető. Kérjük, próbálja meg újra.</p>");
} else {
$('#survey').dialog('close');
$('#survey_thanks').dialog('open');
}
}, "json");
} else {
$("#error_message").html("<p>Kérjük, minden kérdésre adjon választ.</p>");
}
}
}
});
});
You can do it this way
$.post("process_survey.php", $("#popup_survey").serialize()).done( function (data) {
if (data.db_check == 'fail') {
$("#error_message").html("<p>Adatbázisunk nem elérhető. Kérjük, próbálja meg újra.</p>");
} else {
$('#survey').dialog('close');
$('#survey_thanks').dialog('open');
}
});
$(function () {
$('#survey').dialog({
bgiframe: true,
autoOpen: false,
modal: true,
width: 500,
resizable: false,
buttons: {
Submit: function () {
if ($("input[name='elso']:checked").val() !== undefined && $("input[name='masodik']:checked").val() !== undefined && $("input[name='harmadik']:checked").val() !== undefined && $("input[name='negyedik']:checked").val() !== undefined) {
setCookie('POPsurvey', 'POPsurvey', 30);
$.post("process_survey.php", $("#popup_survey").serialize(),
function (data) {
if (data.db_check == 'fail') {
$("#error_message").html("<p>Adatbázisunk nem elérhető. Kérjük, próbálja meg újra.</p>");
} else {
$('#survey').dialog('close');
$('#survey_thanks').dialog('open');
}
}, "json");
} else {
$("#error_message").html("<p>Kérjük, minden kérdésre adjon választ.</p>");
}
}
}
});
});
function (data) must be after serialize
Please remove that alert as the third parameter in the post function like this
$.post("process_survey.php", $("#popup_survey").serialize(),
function (data) {
if (data.db_check == 'fail') {
$("#error_message").html("<p>Adatbázisunk nem elérhető. Kérjük, próbálja meg újra.</p>");
} else {
$('#survey').dialog('close');
$('#survey_thanks').dialog('open');
}
}, "json");
The problem is in your serialize
add this to your code and use serializeObject (not serialize)
$.fn.serializeObject = function(){
var o = {};
var a = this.serializeArray();
$.each(a, function() {
if (o[this.name]) {
if (!o[this.name].push) {
o[this.name] = [o[this.name]];
}
o[this.name].push(this.value || '');
} else {
o[this.name] = this.value || '';
}
});
return o;
};

Categories

Resources