Saving cart details in a database using simplecart.js - javascript

I am using simplecart.js. The cart displays properly. What I want to do now is to retrieve the details in the cart and insert into a database.
Here is my code.
simpleCart({
cartColumns: [
{ 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 }
],
cartStyle: "table",
checkout: {
type: "SendForm",
url: base_url + "Checkout/checkout_function",
method: "POST",
success: base_url + "/Checkout/success",
cancel: base_url + "Checkout/cancel"
}
});
simpleCart.bind('beforeCheckout', function (data) {
data.full_name = document.getElementById("full_name").value;
data.phone = document.getElementById("phone").value;
data.country = document.getElementById("country").value;
data.state = document.getElementById("state").value;
data.city = document.getElementById("city").value;
data.address1 = document.getElementById("address1").value;
data.address2 = document.getElementById("address2").value;
data.zip = document.getElementById("zip").value;
data.address_type = document.getElementById("address_type").value;
});
And the PHP file
for($i=1; $i < $content['itemCount'] + 1; $i++)
{
$prod_name = 'item_name_'.$i; /* product name variable */
$quantity = 'item_quantity_'.$i; /* product quantity variable */
$price = 'item_price_'.$i; /* product price variable */
$shipping = 'simpleCart_shipping_'.$i; /* Shipping cost */
$total = $content[$quantity]*$content[$price]; /* product total price variable (price*quantity) */
$grandTotal += $total; /* accumulating the total of all items */
}
The issue is when I try to echo any of the variables,does not display the content from the cart. Please how do I get the variables to contain the actual content, inserting them into a database will not be a problem.

Related

datatables button change/filter content based on variable sent

I'm using datatables with the buttons plugin. I have two buttons that filter the content that is displayed based on a variable that I need to send to the server, so the ajax url has to change everytime I click one button.
$('#example').DataTable( {
processing: true,
lengthChange: false,
dom: 'Bfrtip',
ajax: {
url: '/get?op=10',
dataSrc: ''
},
columns: [
{ data: 'id' },
{ data: 'name' },
{ data: 'surname' },
{ data: 'phone' },
{ data: 'email' },
{ data: 'nin' }
],
buttons: [
{
text: 'Everyone',
// action ??
},
{
text: 'Owners',
},
{
text: 'Applicants',
}
],
select: true
});
The third button should reset the ajax url to the original one.
public function get_address_book_table($id, $owner = 0) {
$mysqli = $this->aet->getAetSql();
$mysqli->set_charset('utf8');
switch ($owner) {
case 0: $a = $b = NULL; break;
case 1: $a = 'pd.applicant_id'; $b = 'INNER JOIN property_demand pd ON pd.applicant_id = ab.id'; break;
case 2: $a = 'po.owner_id'; $b = 'INNER JOIN property_owner po ON po.owner_id = ab.id'; break;
}
$query = 'SELECT ab.*, sab.*' . $a . '
FROM address_book ab
INNER JOIN staff_address_book sab ON sab.contact_id = ab.id' .
$b . '
WHERE sab.staff_id = ?';
if ($stmt = $mysqli->prepare($query)) {
$stmt->bind_param('s', $id);
$stmt->execute();
$stmt->bind_result($id, $name, $surname, $phone, $email, $nin, $note, $a, $b);
$data = [];
while ($stmt->fetch()) {
$nestedData = [];
$nestedData['id'] = $id;
$nestedData['name'] = $name;
$nestedData['surname'] = $surname;
$nestedData['phone'] = $phone;
$nestedData['email'] = $email;
$nestedData['nin'] = $nin;
$data[] = $nestedData;
}
}
return $data;
}
And the get file:
// address_book table
if ($op === 10) {
$owner = isset( $_GET['owner'] ) ? (int) $_GET['owner'] : 0;
$result = $functions->get_address_book_table($staff->getId(), $owner);
header('Content-type: text/json');
header('Content-type: application/json');
echo json_encode($result);
}
I'm looking for an option for the button plugin that allow me to change the ajax url on click so that the table is refreshed with the new server content.
You need to set a value in the button event, and pass that value as a parameter to the server. Finally, you probably want to trigger the ajax data reload when you click the button. Try something like this:
var filterType = 'all';
$('#example').DataTable( {
processing: true,
lengthChange: false,
dom: 'Bfrtip',
serverSide: true,
ajax: {
url: '/get',
//dataSrc: 'data',
data: function(d) {
d.op = 10;
d.filterType = filterType;
}
},
columns: [
{ data: 'id' },
{ data: 'name' },
{ data: 'surname' },
{ data: 'phone' },
{ data: 'email' },
{ data: 'nin' }
],
buttons: [
{
text: 'Everyone',
action: function(e, dt) { filterType = 'all'; dt.ajax.reload(); }
},
{
text: 'Owners',
action: function(e, dt) { filterType = 'owner'; dt.ajax.reload(); }
},
{
text: 'Applicants',
action: function(e, dt) { filterType = 'app'; dt.ajax.reload(); }
}
],
select: true
});

How can I load rows in JsGrid table that got from php file?

I tried to load rows of data from a table in MySQL. I used jsgrid with PHP.
My two php files connect to the localhost datanase and select rows from the tables using mysqli functions, and copy the result of the query into an array and send by json_encode() to an HTML file where I put the jsgrid code.
Then, I call the html file into other PHP file by <iframe> html tag.
The names of PHP files are:
newsConf, controll and getnewscat
HTML file: basic.html
in controll.php:
public function newsConfig(){
$this->CONN = new Conn();//class from external page to connect DB
try{
$dfnet = $this->CONN->open_connect();
$qnco = mysqli_query($dfnet,"select * from category");
if(!$qnco) return "";
else{
while($qncoarray = mysqli_fetch_row($qnco)){
//here I try copy rows into array
$nnopCo[] = array(
'ID' => $qncoarray['ID'],
'Name' => $qncoarray['Name']
);
}
return $nnopCo;
}
$this->CONN->close_connect($dfnet);
}
catch(Exception $er){
}
in getnewscat.php:
<?php require_once "../../bin/controll.php";
$db_controll = new Controll();
$cat_news = new ArrayObject($db_controll->newsConfig());
header('Content-type: application/json');
echo json_encode($cat_news->getArrayCopy());
?>
in basic.html: is the same file from jsgrid demo, but I change the code in javascript and canceled the db.js file
$(function() {
$("#jsGrid").jsGrid({
height: "70%",
width: "50%",//100%
selecting: false,
filtering: false,
editing: false,
sorting: false,
paging: true,
autoload: true,
pageSize: 15,
pageButtonCount: 5,
controller: {
loadData: function(clients){
var d = $.Deferred();
$.ajax({url: "../bin/getnewscat.php", dataType: "json",function(obj){
for (var i = 0; i < obj.length; i++) {
/*res[i]=data.i;
i++;*/
clients = {
"ID": obj.ID,
"Name": obj.Name
};
}
}
}).done(function(response) {
d.resolve(response.value);
});
return d.promise();
}
In newsConf.php: that file should call basic.html and give the result
by this:
<iframe name="demo" src="jsgrid-1.2.0/demos/basic.html"></iframe>
But the result is empty and I don't know why?, however I change the code but it didn't yield success.
What have I missed here?
Update
See my update below.
The done function should work. Remove success handler and put your mapping into done handler. Then put a debugger into done handler to ensure what you get in a response. Then map the response accordingly and resolve the deferred.
loadData: function(clients){
var d = $.Deferred();
$.ajax({
url: "../bin/getnewscat.php"
}).done(function(response) {
// put a debugger here to ensure that your response have 'value' field
var clients = $.map(response.value, function(item) {
return {
ID: item.SomeID,
Name: item.SomeName
};
});
d.resolve(clients);
});
return d.promise();
}
I'm not sure whether you need a mapping or not. Maybe you can remove it in the end. But do everything in the done handler and check the format of the response.
Sorry for my delay, but I think I got where's my mistake!
I fixed it and I got what I missed,
In controll.php file, I used mysqli_fetch_row() function, but I forgot I send the data in a named array, so I changed it to mysqli_fetch_assoc() function.
and about basic.html I changed it to:
<script>
$(function() {
{
$("#jsGrid").jsGrid({
height: "70%",
width: "50%",//100%
selecting: false,
filtering: false,
editing: false,
sorting: false,
paging: true,
autoload: true,
pageSize: 15,
pageButtonCount: 5,
controller: {
loadData: function(filter) {
//here how I fix it!
return $.ajax({url: "../bin/getnewscat.php",data:filter
});
}
},
////////////////////////////////////////////////////////////
fields: [
{ name: "ID", type: "number", width: 50 },
{ name: "Name", type: "text", width: 50},
{ type: "control", modeSwitchButton: false, deleteButton: false }
]
});
$(".config-panel input[type=checkbox]").on("click", function() {
var $cb = $(this);
$("#jsGrid").jsGrid("option", $cb.attr("id"), $cb.is(":checked"));
});
});
</script>
but I think it's not secure, how could I make it more secure?
I was having the same issue. However once I added the return to $.ajax line all I get is blank lines but the grid is trying to render something. See image below.
PHP Code Below:
$sql = "SELECT e.estimateid, e.customerid, e.compid, cu.first_name,cu.last_name,e.reference_num, e.estimate_date, e.expiry_date, e.hours, e.sales_person, e.project_name
FROM estimates AS e INNER JOIN company AS c ON e.compid = c.compid
INNER JOIN customers AS cu ON e.customerid = cu.customerid";
$resultsE = $conn->query($sql);
$rows = array();
while ($r = $resultsE->fetch_assoc()){
$rows[] = $r;
}
$data = array($rows);
}
//header("Content-Type: application/json"); //If I uncomment this line the Grid says No Results.
echo json_encode($data);
JS Code Below:
$(function() {
$("#jsGrid").jsGrid({
height: "90%",
width: "98%",
filtering: true,
inserting: false,
editing: false,
sorting: true,
paging: true,
autoload: true,
pageSize: 10,
pageButtonCount: 5,
//deleteConfirm: "Do you really want to delete client?",
controller: {
loadData: function(filter) {
return $.ajax({url: "/js/jsgrid/estimates/index.php",data: filter });
},
/*insertItem: function(item) {
return $.ajax({
type: "POST",
url: "/estimates/",
data: item
});
},
updateItem: function(item) {
return $.ajax({
type: "PUT",
url: "/estimates/",
data: item
});
},
deleteItem: function(item) {
return $.ajax({
type: "DELETE",
url: "/estimates/",
data: item
});
}*/
},
fields: [
{ name: "estimateid", type: "number", width: 10, title: "EstId" },
{ name: "customerid", type: "number", width: 10, title: "CustId" },
{ name: "compid", type: "number", width: 10, title: "CompId"},
{ name: "first_name", type: "text", width: 50, title: "First Name" },
{ name: "last_name", type: "text", width: 50, title: "Last Name" },
{ name: "reference_num", type: "text", width: 12, title: "Ref.#" },
{ name: "estimate_date", type: "text", width: 12, title: "Est. Date" },
{ name: "expiry_date", type: "text", width: 12, title: "Exp. Date" },
{ name: "hours", type: "number", width: 10, title: "Hours" },
{ name: "sales_person", type: "text", width: 50, title: "Sales" },
{ name: "project_name", type: "text" , width: 50, title: "Project"},
{ type: "control" }
]
});
});

Why is the select display showing the value instead of the label?

I'm trying to use a select with inline editing. I have gotten this to display properly using the popup for editing, but I want it all to be inline and submit on blur. My data includes both an ID and a name for each dropdown item, which I have in an object that looks like { label: "blah", value: "blah" } etc.
However, in the DataTable the dropdowns are all being displayed with the ID instead of the label as the default value. I don't want users to see the id. I tried setting the editor field name to be the label and the DataTable column to be the value, which seemed to work for the popup but for inline editing I get the error "Uncaught Unable to automatically determine field from source. Please specify the field name".
My initializations look like this:
editor = new $.fn.dataTable.Editor({
ajax: 'url',
table: '#table',
idSrc: 'id',
fields: [{
label: "Location",
name: "location_name", //this is where the problem is, I think
type: "select",
ipOpts: locationList
}]})
$('#table').dataTable({
dom: "Tfrtip",
"searching": false,
"ajax": {
"url": "url",
"type": "GET"
},
"columnDefs": [
{ "visible": false, "targets": [8] }
],
"columns": [
{ "data": "location_id" }
])}
If I change the DataTable to use the name, the display is correct, but I get the name submitted to the database instead of the ID, and I need the ID.
What should I do?
I did it like this, it's messy but works:
Each editable object has it's own span class. An ID that relates to the parent object. A key that relates to the object that is being updated. And then of course the data.
<td><span class="dcmeta" data-value="'.$row['DATACENTER'].'" data-type="select" id="'.$row['CLUSTERNAME'].'" key="DATACENTER">'.$row['DATACENTER'].'</span></td>
<td><span class="tiermeta" data-value="'.$row['TIER'].'" data-type="select" id="'.$row['CLUSTERNAME'].'" key="TIER">'.$row['TIER'].'</span></td>
Javascript:
<script type="text/javascript">
jQuery(document).ready(function() {
$.fn.editable.defaults.mode = 'popup';
$('.xedit').editable();
$('.tiermeta').editable({
title: 'Test title',
source: [
{value: 'Tier 1', text: 'Tier 1'},
{value: 'Tier 2', text: 'Tier 2'},
]
});
$('.dcmeta').editable({
title: 'Test title',
source: [
{value: 'DC1', text: 'DC1'},
{value: 'DC2', text: 'DC2'},
]
});
$(document).on('click','.editable-submit',function(){
var key = $(this).closest('.editable-container').prev().attr('key');
var x = $(this).closest('.editable-container').prev().attr('id');
var y = $('.input-metadata').val();
var z = $(this).closest('.editable-container').prev().text(y);
$.ajax({
url: "process.php?id="+x+"&data="+y+"&key="+key,
type: 'GET',
success: function(s){
if(s == 'status'){
$(z).html(y);}
if(s == 'error') {
alert('Error Processing your Request! ');}
},
error: function(e){
alert('Error Processing your Request!! ');
}
});
});
});
</script>
PHP:
<?php
$conn = sqlsrv_connect( $serverName, $connectionInfo );
if( $conn === false ) {
die( print_r( sqlsrv_errors(), true));
}
if($_GET['id'] and $_GET['data'] and $_GET['key'])
{
$id = $_GET['id'];
$data = $_GET['data'];
$key = $_GET['key'];
$sql = "update CLUSTER set $key='$data' where CLUSTERNAME='$id'";
echo 'success';
$stmt = sqlsrv_query( $conn, $sql );
if( $stmt === false) {
die( print_r( sqlsrv_errors(), true) );
}
}
?>

Paging not working, Extjs grid

I made an extjs grid with a bottom toolbar to create a paging behavior, but it's not working and I don't know where is the problem, I've already done it with local data, but when i used a database it didn't work, it shows all the data at once.
Here's the code :
Ext.require([ 'Ext.data.*', 'Ext.grid.*' ]);
Ext.onReady(function() {
var categoriesStore = Ext.create('Ext.data.JsonStore', {
autoLoad: true,
pageSize : 10,
proxy: {
type: 'ajax',
url: 'GridDataBase/categories.php',
reader: {
type: 'json',
totalProperty: 'total',
root: 'categories',
idProperty: 'name'
}
},
fields : ['id','name']
});
var panelOfData = Ext.create('Ext.grid.GridPanel',{
store : categoriesStore,
columns : [ {
id : 'id',
header : "Id",
width : 20,
sortable : true,
dataIndex : 'id'
}, {
id : 'name',
header : "Category Name",
width : 75,
sortable : true,
dataIndex : 'name'
} ],
//stripeRows : true,
//paging bar on the bottom
bbar: Ext.create('Ext.PagingToolbar', {
store: categoriesStore,
displayInfo: true,
displayMsg: '{0} - {1} of {2}',
emptyMsg: "No categories to display"
}),
autoExpandColumn : 'name',
height : 350,
width : 600,
renderTo : 'grid-ex',
title : 'Categories'
});
categoriesStore.loadPage(1);
console.log(categoriesStore.count()); // the log here shows 0
});
Here's the PHP file :
function GetCategories() {
$query = "SELECT id, name FROM categorie";
$categories = array("categories" => array());
#mysql_connect("localhost","superuser","SS4") or die();
mysql_select_db("dbz"); !mysql_error () or die();
$result = mysql_query($query);
$num = mysql_num_rows($result);
$i = 0;
while ($row = mysql_fetch_assoc($result)) {
$categories["categories"][$i] = $row;
$i++;
}
return json_encode($categories);
}
echo GetCategories();
Extjs code sends some additional params for implementing the paging on server start, limit and these params have to be used in your query to send back records upto the pagesize limit of store. Server response should also send back a property with total number of records (to be assigned to totalProperty of store) which will be used to calculate number of pages.
store.load({
params:{
start:0,
limit: itemsPerPage
}
});
Hope it helps!!
You havent implemented paging on server side. Try this:
function GetCategories($start, $limit) {
$query = "SELECT id, name FROM categorie LIMIT $start, $limit";
$categories = array("categories" => array());
#mysql_connect("localhost","superuser","SS4") or die();
mysql_select_db("dbz"); !mysql_error () or die();
$result = mysql_query($query);
$num = mysql_num_rows($result);
$i = 0;
while ($row = mysql_fetch_assoc($result)) {
$categories["categories"][$i] = $row;
$i++;
}
return json_encode($categories);
}
$start = isset($_GET['start']) ? $_GET['start'] : 0;
$limit = isset($_GET['limit']) ? $_GET['limit'] : 0;
echo GetCategories($start, $limit);

jqgrid addrowdata after calling ajax

I have question regarding adding another rowdata at the end of my jqgrid. What I wanted to do is that everytime I do a simple search on a particular transaction, and display it on my jqgrid, i want to have another row at the end which have my total computations. Below is my complete jqgrid code:.
$("#tblSupplier").jqGrid({
url: '',
datatype: 'local',
jsonReader : {
root: function(obj) {
var root = [];
if ('error' in obj)
{
showMessage(obj.error['class'] + ' error: ' + obj['error']['msg']);
}
else
{
var totalBdFt = '';
var bdft=0;
var amt=0;
var totalAmount = '';
$.each(obj['result']['main']['rowdata'], function(rowIndex, rowDataValue) {
var row = {};
$.each(rowDataValue, function(columnIndex, rowArrayValue) {
var fldName = obj['result']['main']['metadata']['fields'][columnIndex].name;
row[fldName] = rowArrayValue;
if (fldName == 'transaction_date'){
$('#tallyDate').val(rowArrayValue);
}
if (fldName == 'supplier_name'){
$('#supplierName').val(rowArrayValue);
}
if (fldName == 'board_foot'){
bdft = parseFloat(bdft) + parseFloat(rowArrayValue);
}
if (fldName == 'total_amount'){
amt = parseFloat(amt) + parseFloat(rowArrayValue);
}
});
root[rowIndex] = row;
$('#totalBdft').val(parseFloat(bdft));
$('#totalAmt').val(parseFloat(amt));
});
};
return root;
},
page: "result.main.page",
total: "result.main.pageCount",
records: "result.main.rows",
repeatitems: false,
id: "0"
},
serializeGridData: function(postData) {
var jsonParams = {
'SessionID': $.cookie("SessionID"),
'dataType': 'data',
'simple_search_value':trim($("#searchSupAny").val()),
'recordLimit': postData.rows,
'recordOffset': postData.rows * (postData.page - 1),
'rowDataAsObjects': false,
'queryRowCount': true,
'sort_fields': postData.sidx
};
return 'json=' + JSON.stringify(jsonParams);
},
loadError: function(xhr, msg, e) {
showMessage('HTTP error: ' + JSON.stringify(msg) + '.');
},
colNames:['Transaction Num', 'Wood Classification', 'Specie', 'Total Board Foot', 'Price', 'Total Amount'],
colModel:[
{name:'transaction_num'},
{name:'wood_classification_desc'},
{name:'wood_specie_desc'},
{name:'board_foot'},
{name:'price'},
{name:'total_amount'}
],
viewrecords: true,
sortname: 'transaction_num',
sortorder: 'desc',
loadonce:false,
height:'100%',
caption: "sample summary"
});
var newRowData = [{ "wood_classification_desc": 'total should b here', "wood_specie-desc": "total bdft here", "total_amount": "total amount here"}];
$("#tblSupplier").addRowData('transaction_num',newRowData);
})
my newRowData displays only on load, but after I do a simple search, it will also gone. But my jqgrid with ajax data working good. So how should I do it to maintain my additional row everytime I call ajax?

Categories

Resources