Add function before checkout with simplecartjs - javascript

I use Simplecartjs and I see they have custom to add function beforeCheckout.
<script>
//<![CDATA[
simpleCart({
// array representing the format and columns of the cart, see
// the cart columns documentation
cartColumns: [
{view:"image" , attr:"thumb", label: false },
{ attr: "name" , label: "Name" },
{ attr: "price" , label: "Price", view: 'currency' },
{ view: "decrement" , label: false },
{ attr: "quantity" , label: "Qty" },
{ view: "increment" , label: false },
{ attr: "total" , label: "SubTotal", view: 'currency' },
{ view: "remove" , text: "Remove" , label: false }
],
// "div" or "table" - builds the cart as a table or collection of divs
cartStyle: "div",
// how simpleCart should checkout, see the checkout reference for more info
checkout: {
type: "PayPal" ,
email: "you#hello.com"
},
// set the currency, see the currency reference for more info
currency: "USD",
// collection of arbitrary data you may want to store with the cart,
// such as customer info
data: {},
// set the cart langauge (may be used for checkout)
language: "english-us",
// array of item fields that will not be sent to checkout
excludeFromCheckout: [],
// custom function to add shipping cost
shippingCustom: null,
// flat rate shipping option
shippingFlatRate: 0,
// added shipping based on this value multiplied by the cart quantity
shippingQuantityRate: 0,
// added shipping based on this value multiplied by the cart subtotal
shippingTotalRate: 0,
// tax rate applied to cart subtotal
taxRate: 0,
// true if tax should be applied to shipping
taxShipping: false,
// event callbacks
beforeAdd : null,
afterAdd : null,
load : null,
beforeSave : null,
afterSave : null,
update : null,
ready : null,
checkoutSuccess : null,
checkoutFail : null,
beforeCheckout : null
});
//]]>
</script>
But I do not how to add new function for it. Write new script? For example, add function to alert 5s with content: "You are redirecting to Paypal" before redirect to Paypal.
Thank you very much.

include this
simpleCart.bind( 'beforeCheckout' , function( data ){
alert('You are redirecting to Paypal');
});
with timeOut looks like so:
simpleCart.bind( 'beforeCheckout' , function( data ){
setTimeout(function(){
alert('You are redirecting to Paypal')
}, 5000); // 5 seconds
});
at the end of the last .js file or create a new .js file which you include as last file:

Related

Reset Search Results

Good morning. I made a data search & filter with datatables and it worked .. but when I moved the page and returned to that page the data was still stuck (not reset). In view I made it like the following image:
and in the js file I made it like this
brandmanage = $('#brandmanage').DataTable({
dom : 'rtpi',
pageLength: {{ $limit ?? '10' }},
language : {
paginate : {
previous : '<i class="fa fa-angle-left"></i>', // or '←'
next : '<i class="fa fa-angle-right"></i>', // or '→'
},
},
processing : true,
drawCallback : function( settings ) {
$('#lengthInput option[value={{ $limit ?? '10' }}]').attr('selected','selected');
},
serverSide : true,
stateSave : true,
ajax : {
url : "{{ route('lms.brand.getdata',['pfx'=>$pfx]) }}",
dataType : "json",
type : "POST",
data : { _token: "{{csrf_token()}}" }
},
columns : [
{ data : "brand" },
{ data : "corporate" },
{ data : "num_of_company" },
{ data : "primary" },
{ data : "secondary" },
{ data : "status" },
{ data : "action",
orderable : false,
className : "text-center",
},
],
});
$('#brandDataLength').on('change', function () {
brandmanage.page.len( $(this).val() ).draw();
});
$('#searchBrand').on('keyup', function () {
brandmanage.search( this.value ).draw();
});
What do I do so that when I have moved pages, the search results can be reset?
If you change stateSave to false, then dataTables will not remember the selected filters etc. Thereby the search results will be reset when you reload the page.

Adding form data inputs to jqGrid

I am trying to add the data obtained from the form and display it to JQGrid.
I have the following elements in my Form.
Textbox for username
Datepicker for date of birth
Combobox for selecting the country.
Two buttons Add and Clear button.
Whenever i click the Add button ,it has to add a row to the JQGrid.Whenver i click the clear button it has to reset the entire table.
Currently,I am trying to display the data from the form to the row.
Below is my effort till now.
<script>
$(function() {
$( "#pwd" ).datepicker();
var source = [{
text: "Australia",
value: 0
},
{
text: "India",
value: 1
},
{
text: "United States",
value: 2
},
{
text: "United Kingdom",
value: 3
}];
$("#jqxComboBox").jqxComboBox({
source: source,
theme: 'energyblue',
width: '240px',
height: '30px',
displayMember: 'text',
selectedIndex: 0,
valueMember: 'value'
});
$('#add').click(function(){
name=$('#name').val();
date=$('#pwd').val();
country=$('#jqxComboBox').val();
alert(name);
$('#jqGrid').jqGrid('addRowData',name,date,country);
}); });
</script>
<style type="text/css">
</head>
<body>
<div class="container">
<h2>Horizontal form</h2>
<form class="form-horizontal" role="form" id="add_form">
<input type="text" id="name"></input>
<input type="text" id="pwd"></input>
<div id="jqxComboBox"></div>
<input type="submit" value="add">
<input type="submit" value="reset">
</div>
</form><table id="jqGrid">
</table>
</body>
</html>
May be you should init jqGird first and run code like below :
$(function() {
$("#jqGrid").jqGrid({
'datatype' : 'local',
// if there is no data at the beginning, just define an empty array [],
// or you can set init data with data option below
'data' : [ {
'name' : 'testUser',
'date' : '15/4/2016',
'country' : 'somewhere'
} ],
'colNames' : [ 'Name', 'Date', 'Country' ],
'colModel' : [ {'name' : 'name'}, {'name' : 'date'}, {'name' : 'country'} ],
'loadComplete' : function() { // You can add data manually using code below.
// You can define a datarow variable as single object and also an
// array of objects.
// array data example: var datarow = [{"name":"addedName",
// "date":"16/4/2016", "country":"any"},
// {"name":"addedName2", "date":"16/4/2016", "country":"any2"}];
var datarow = {
"name" : "addedName",
"date" : "16/4/2016",
"country" : "any"
};
// second parameter of method below is rowid just for generate id
// attribute of tr element.
// if keep rowid variable as undefined, jqGrid will generate a
// random id instead.
var rowid;
// last paremeter tell jqGrid add new data after last row.
$("#jqGrid").jqGrid("addRowData", rowid, datarow, "last");
}
});
});
<script src="http://www.trirand.com/blog/jqgrid/js/jquery.js"></script>
<script src="http://www.trirand.com/blog/jqgrid/js/jquery.jqGrid.js"></script>
<table id="jqGrid"></table>

How do I hide certain rows in a ui-grid based on its values?

I have a simple UI grid with these options:
$scope.transactionGrid = {
enableSorting : true,
enableColumnResize : true,
enableScrollbars : true,
enablePaginationControls : false,
minRowsToShow : 6,
onRegisterApi : function(gridApi) {
$scope.gridEventsApi = gridApi;
}
};
I want to hide rows which have a specific value, deleted: "y".
$scope.transactionGrid.data = [
{ Name: "First", deleted: "y" },
{ Name: "Second", deleted: "y" },
{ Name: "Third", deleted: "n" },
{ Name: "Fourth", deleted: "n" }
];
Without actually changing the data, can it be filtered out from rows?
One way is to adjust the row-repeater-template to check for some row-specific value and make the row show/hide that way.
I created a Plunkr showcasing a possible solution.
First you need to create your row-value-checker-function:
appScopeProvider: {
showRow: function(row) {
return row.deleted !== 'y';
}
},
Then you adjust their template by adding that check to their row-repeater
$templateCache.put('ui-grid/uiGridViewport',
...
ng-if=\"grid.appScope.showRow(row.entity)\"
...
}
I know you specifically said "without actually changing the data", but assigning a filtered dataset to the grid would not change the dataset, just the data for the grid. Also it might be a relevant and valid solution for other cases like this.
I forked CMR's Plunk to demonstrate this: http://plnkr.co/edit/NntwWb?p=preview
The key part is just adding a filter when assigning the dataset:
$scope.gridOptions = {
data: $scope.myData.filter(function(row) {
return row.deleted !== "y";
})
};
You can hide it by creating cell templates and hide it based on row value for every field:
$scope.transactionGrid = {
enableSorting : true,
enableColumnResize : true,
enableScrollbars : true,
enablePaginationControls : false,
minRowsToShow : 6,
onRegisterApi : function(gridApi) {
$scope.gridEventsApi = gridApi;
}
// Column template definitions:
columnDefs: [
{
name: 'Name',
displayName: 'Name',
cellTemplate : '<div ng-if="row.entity.deleted">{{row.entity.Name}}</div>'
}
]
};
I made a Plunk to demonstrate a viable technique to solve this: https://plnkr.co/edit/XQRC45vaiZCySZYkEGrz?p=preview

How to calculate row sum on user entry in free jqgrid

Row sum should calculated if price or quantity is changed.
Formatter is created according to How to access other row data from a cell's custom formatter in JqGrid
In inline and row editing modes row sum doesnt change.
Row sum column is read only and does not have id assigned. So it is difficult to create script to change it.
How to fix this so that row sum is calculated on edit ?
Testcase is in http://jsfiddle.net/ex6158L1/4/ containing
javascript
var serverResponse = {
"page": "1",
"records": "3",
"rows": [
{ "Id": "1", Quantity:4, Price : 23.33 },
{ "Id": "2", Quantity:4.55, Price : 76.66 }
]
},
$grid = $("#categorysummary");
function sumFmatter (cellvalue, options, rowObject) {
return options.rowData.Quantity *
options.rowData.Price;
}
$grid.jqGrid({
url: "/echo/json/", // use JSFiddle echo service
datatype: "json",
mtype: "POST", // needed for JSFiddle echo service
pager: '#pager',
postData: {
json: JSON.stringify(serverResponse) // needed for JSFiddle echo service
},
//colNames: ["Quantity", "Price"],
colModel: [
{ name: 'Id', hidden: true },
{ name: 'Quantity', editable: true},
{ name: 'Price', editable: true },
{ name: "Sum", formatter: sumFmatter, editable: "readonly" }
],
jsonReader: {
id: 'Id',
repeatitems: false
},
sortname: 'Id',
viewrecords: true
})
.jqGrid("navGrid",'#pager')
.jqGrid("inlineNav",'#pager');
and css
<div class="container">
<div id="pager"></div>
<table id="categorysummary"></table>
</div>
The first problem, which you have, is the bug in free jqGrid, which follows that options.rowData was not filled inside of setRowData. I posted the corresponding fix to GitHub to eliminate the problem.
The next problem is the requirement to reformat the data of editable: "readonly". Form editing do this, but not inline editing. One can use either editable: "hidden" or to add the option
inlineEditing: {
extraparam: { Sum: "" }
}
which extend the results of inline editing with the dummy value "" for Sum column. It force reformatting of the value in the Sum column.
I would recommend you additionally to change the formatter sumFmatter which you use to
function sumFmatter (cellvalue, options, rowObject) {
var quantity = parseFloat(options.rowData.Quantity || 0),
price = parseFloat(options.rowData.Price || 0);
return (quantity * price).toFixed(2);
}
see the demo http://jsfiddle.net/OlegKi/ex6158L1/7/ or to
function sumFmatter (cellvalue, options, rowObject, action) {
var quantity = parseFloat(options.rowData.Quantity || 0),
price = parseFloat(options.rowData.Price || 0);
return $.fn.fmatter.call(this, "number", quantity * price,
options, rowObject, action);
}
where I called formatter: "number" to format the results of the multiplication (quantity * price).
See the resulting demo http://jsfiddle.net/OlegKi/ex6158L1/10/

Kendo UI grid is not firing create, update and destroy events

i tried to fire the Create event in transport section of the Kendo Datagrid. I tried to read the whole documentation for Kendo Datagrid but i'm not able to fire create, update and destroy events.
Could somebody please tell me what can be wrong in my code?
Thanks for any advice.
Here is the source of method:
/**
* Fill data grid by users
* #param {Number} a
* #param {Number} b
* #return {Number} sum
*/
$scope.initTable = function() {
// get access token from localstorage
var token = localStorage.getItem($rootScope.lsTokenNameSpace);
// set pagination data
var paginationData = {
"token" : token,
"data" : {
"page" : 1,
"items_per_page" : 20
}
};
$("#grid").kendoGrid({
dataSource : {
transport : {
// read list
read : function(options) {
$.ajax({
url: $rootScope.apiBaseUrl + "user/list",
dataType: "json",
type : "POST",
data: JSON.stringify(paginationData),
success: function(response) {
console.log("List of users succesfully obtained");
console.log(response.result);
// pass response to model
options.success(response);
// $notification.enableHtml5Mode();
},
error: function(error) {
console.log("user list request error");
console.log(error);
$notification.error( "User list cannot be loaded", "Please try again in a minute.");
}
});
},
// create list item
create : function(options) {
console.log("Create function");
},
// update list item
update : function(options) {
console.log("Update function");
},
// destroy list item
destroy: function(options) {
console.log("Destroy function");
},
// important for request
parameterMap: function(options, operation) {
console.log(options);
console.log(operation);
if (operation === "read") {
// send parameter "access_token" with value "my_token" with the `read` request
return {
data: paginationData,
token: token
};
} else
return {
data: kendo.stringify(options.models),
access_token: "my_token"
};
}
},
// data model
schema : {
// JSON data parrent name
data : "result",
model : {
fields : {
id : {
type : "integer",
editable: false,
nullable: true
},
username : {
editable: "inline",
type : "string",
validation: {
required: {
message: "Please enter a Username"
}
}
},
name : {
type : "string"
},
surname : {
type : "string"
},
email : {
type : "string"
},
created : {
type : "string"
},
role : {
type : "string"
}
}
}
},
// data source settings
pageSize : 10,
editable: true,
serverPaging : false,
serverFiltering : false,
serverSorting : false,
batch : true
},
// data grid settings and customization
toolbar : ["create"],
editable: true,
height : 350,
filterable : true,
sortable : true,
pageable: {
refresh: true,
pageSizes: true,
buttonCount: 5
},
selectable: "multiple, row",
// columns
columns : [ {
field : "id",
title : "ID"
}, {
field : "username",
title : "Username"
},{
field : "name",
title : "Name"
},{
field : "surname",
title : "Email"
},{
field : "email",
title : "Email"
},{
field : "created",
title : "created at"
},{
field : "role",
title : "Role"
},
{ // table action buttons
command: [
{name: "edit"},
{name: "destroy", text: "Remove"},
{name: "detail", click:redirectToUserDetal},
] ,
// Action column customization
title: "Action",
width: "300px"
}
]
});
};
});
have faced same issue. But I have solved using this.
To fire create/delete/update we need to specify schema in dataSource( in schema we should mention atleast what is id field).
schema: { model: { id: "StudentID" } }
Code:
var dataSource = new kendo.data.DataSource({
transport: {
read: function (options) {
alert("read");
},
create: function (options) {
alert("create");
},
update: function (options) {
alert("update"); },
destroy: function (options) {
alert("destroy"); }
},
schema: {
model: {
id: "StudentID"
}
}
You configured your dataSource for batch mode, batch: true, but you provided no way to save the changes. Remember that batch mode queue's up all of your create, update, and destroy actions. They are all fired at once when the dataSource is synced, (i.e. dataSource.sync()).
The simplest way to enable this, given your config, is add 'save' to your toolbar. You might also want to include 'cancel' as well.
toolbar : ["create", "save", "cancel"],
Make sure your id is set on the objects that your read action is returning.
I had the same issue with my update action not being hit. I checked Fiddler and the POST was being made, but my id field was not set. I traced this back and found that my id was not being set on the objects when they were returned by my read action.
Without the id field being sent in the POST, my controller didn't recognize the parameters, thus not hitting my action.

Categories

Resources