I need help trying to print certain fields from the table using javascript. Mainly each ticket number that is generated with the name and phone number of the person and another function to just print the address of the person that purchased the tickets. I have been racking my brain for a couple of days and think I just need some fresh eyes to help me out. Here s the code I have been working with, I will admit that I am somewhat of a newb! i just a little help. Thanks.
<div class="span16">
<div style="float:right;">
Printer 3 Checked
<!--Printer 2 Checked-->
</div>
<h1>Orders</h1>
<hr/>
<?php echo $this->element('pager'); ?>
<table class="table table-striped table-bordered table-condensed">
<thead>
<tr>
<th>Order</th>
<th>Raffle</th>
<!--<th>Transaction</th>-->
<th style="white-space:nowrap;">Tickets</th>
<th>Total</th>
<th>Date</th>
<th>Status</th>
<th>Name</th>
<th style="white-space:nowrap;width:200px;">Address</th>
<th style="white-space:nowrap;width:100px;">Print</th>
<th style="white-space:wrap;width:100px;">Address Label</th>
</tr>
</thead>
<tbody>
<?php
$i = 0;
$t = 0;
foreach ($orders as $order):
$rowclass = 'orders';
if ($i++ % 2 == 0) {
$rowclass .= ' orders-even';
} else {
$rowclass .= ' orders-odd';
}
$id = $order['Order']['id'];
//$transaction_number = $order['Order']['transaction_number'];
$quantity = $order['Order']['quantity'];
$total = '$'.number_format($order['Order']['total'], 2, '.', ',');
$date = '<div class="date">'.date('m/d/y', strtotime($order['Order']['modified'])).' </div>';
$date .= '<div class="time">'.date('h:i a', strtotime($order['Order']['modified'])).' </div>';
$status = '<div class="status status-'.strtolower($order['Order']['status']).'">'.$order['Order']['status'].' </div>';
$name = '<div class="name">'.$order['Order']['first_name'].' '.$order['Order']['last_name'].' </div>';
$name .= '<div class="email">'.$order['Order']['email'].' </div>';
$phone = '<div class="phone">'.$order['Order']['phone'].' </div>';
if (!empty($phone)) {
$name .= '<span class="phone">'.$phone.'</span>';
}
$address = '<div class="address">'.$order['Order']['address'].'</div>';
if (!empty($order['Order']['address2'])) {
$address .= '<div class="address">'.$order['Order']['address2'].'</div>';
}
$csz = $order['Order']['city'];
if (!empty($order['Order']['state'])) {
$csz .= ' '.$order['Order']['state'];
}
if (!empty($order['Order']['zip'])) {
$csz .= ', '.$order['Order']['zip'];
}
$address .= '<div class="csz">'.$csz.'</div>';
if (empty($order['Order']['address2'])) {
$address .= '<div class=""></div>';
}
$raffle = $order['Raffle']['name'];
if (!empty($order['Order']['printed'])) {
$printed = '<a href="/orders/view/'.$order['Order']['id'].'/printer1" class="btn btn-printed">';
$printed .= 'Tickets';
$printed .= '</a>';
} else {
$printed = '<a href="/orders/view/'.$order['Order']['id'].'/printer1" class="btn">';
$printed .= 'Tickets';
$printed .= '</a>';
}
/* settings for address labels */
if (!empty($order['Order']['printed2'])) {
$printed2 = '<a href="/orders/address/'.$order['Order']['id'].'" class="btn btn-printed">';
$printed2 .= 'Address';
$printed2 .= '</a>';
} else {
$printed2 = '<a href="/orders/address/'.$order['Order']['id'].'/" class="btn">';
$printed2 .= 'Address';
$printed2 .= '</a>';
}
?>
<tr class="<?php echo $rowclass; ?>" rel="tickets-<?php echo $order['Order']['id']; ?>">
<?php echo '<td align="center"><input type="checkbox" name="data[Order][][id]" id="OrderId'.$order['Order']['id'].'" value="'.$order['Order']['id'].'"></td>'; ?>
<?php echo '<td>'.$raffle.'</td>'; ?>
<?php //echo '<td>'.$transaction_number.'</td>'; ?>
<?php echo '<td nowrap>'; ?>
<?php foreach ($order['Ticket'] as $ticket): ?>
<?php echo $ticket['reference_number']; ?>
<script>
function printTickets()
{
window.print()
}
</script>
<input type="button" value="Print" onclick="printMe()"><br />
<?php endforeach; ?>
<?php echo '</td>'; ?>
<?php echo '<td>'.$total.'</td>'; ?>
<?php echo '<td>'.$date.'</td>'; ?>
<?php echo '<td>'.$status.'</td>'; ?>
<?php echo '<td>'.$name.'</td>'; ?>
<?php echo '<td>'.$address.'</td>'; ?>
<?php echo '<td>'.$printed.'</td>'; ?>
<?php echo '<td>'.$printed2.'
</td>';?>
</tr>
<?php endforeach; ?>
</tbody>
</table>
<?php echo $this->element('pager'); ?>
<?php $this->start('sidebox.orders');?>
<div class="well">
<?php echo $this->Html->link(__('New Order', true), array('action' => 'add'), array('class' => 'btn primary')); ?>
<?php echo $this->Html->link(__('List Orders', true), array('controller' => 'orders', 'action' => 'index'), array('class' => 'btn')); ?>
<?php echo $this->Html->link(__('New Order', true), array('controller' => 'orders', 'action' => 'add'), array('class' => 'btn')); ?>
<?php echo $this->Html->link(__('List Tickets', true), array('controller' => 'tickets', 'action' => 'index'), array('class' => 'btn')); ?>
<?php echo $this->Html->link(__('New Ticket', true), array('controller' => 'tickets', 'action' => 'add'), array('class' => 'btn')); ?>
</div>
<?php $this->end(); ?>
<?php $this->append('sidebox', $this->fetch('sidebox.orders')); ?>
</div>
<script>
$('.tickets').hide();
$(function(){
$('.tickets-link').click(function(e){
e.preventDefault();
$('.'+$(this).attr('rel')).slideToggle();
});
$('.btn-printed, .btn-multiprint').addClass('disabled');
$(':checkbox').change(function(){
if ($(':checked').length) {
$('.btn-multiprint').removeClass('disabled');
} else {
$('.btn-multiprint').addClass('disabled');
}
});
$('.btn-multiprint').click(function(e){
e.preventDefault();
var ids = [];
$(':checked').each(function(){
ids.push($(this).attr('value'));
});
window.location = $(this).attr('href')+ids.join(',')+'/'+$(this).attr('id').replace('multiprint','printer');
});
});
</script>
I may be missing something and maybe you have thought of this, but i feel I had to do something similar years back... why not use a print stylesheet to hide that which you don't want printed and show what you do? You could try dynamically loading a different print stylesheet if different clicks have different actions. How to load up CSS files using Javascript?
Related
i have a table in php whose data comes from sql database, so i have kept a pagination for the table because the data is long
<?php
require_once "config.php";
$perpage = 5;
if(isset($_GET['page']) & !empty($_GET['page'])){
$curpage = $_GET['page'];
}else{
$curpage = 1;
}
$start = ($curpage * $perpage) - $perpage;
$sql = "SELECT * FROM `registers` LIMIT $start, $perpage";
$PageSql = "SELECT * FROM `registers`";
$pageres = mysqli_query($link, $PageSql);
$totalres = mysqli_num_rows($pageres);
if($result = mysqli_query($link, $sql)){
if(mysqli_num_rows($result) > 0){
echo "<table class='table'>";
echo "<thead>";
echo "<tr>";
echo "<th class='serial'>ID</th>";
echo "<th>Name</th>";
echo "<th>Phone Number</th>";
echo "<th>Email</th>";
echo "<th>Action</th>";
echo "</tr>";
echo "</thead>";
echo "<tbody>";
while($row = mysqli_fetch_array($result)){
echo "<tr>";
echo "<td>" . $row['id'] . "</td>";
echo "<td>" . $row['firstname'] . "</td>";
echo "<td>" . $row['address'] . "</td>";
echo "<td>" . $row['id'] . "</td>";
echo "<td>";
echo "<a href='read.php?id=". $row['id'] ."' title='View Record' data-toggle='tooltip'><span class='glyphicon glyphicon-eye-open'></span></a>";
echo "</td>";
echo "</tr>";
}
echo "</tbody>";
echo "</table>";
// Free result set
mysqli_free_result($result);
} else{
echo "<p class='lead'><em>No records were found.</em></p>";
}
} else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
?>
<nav aria-label="Page navigation">
<ul class="pagination">
<?php if($curpage != $startpage){ ?>
<li class="page-item">
<a class="page-link" href="?page=<?php echo $startpage ?>" tabindex="-1" aria-label="Previous">
<span aria-hidden="true">«</span>
<span class="sr-only">First</span>
</a>
</li>
<?php } ?>
<?php if($curpage >= 2){ ?>
<li class="page-item"><a class="page-link" href="?page=<?php echo $previouspage ?>"><?php echo $previouspage ?></a></li>
<?php } ?>
<li class="page-item active"><a class="page-link" href="?page=<?php echo $curpage ?>"><?php echo $curpage ?></a></li>
<?php if($curpage != $endpage){ ?>
<li class="page-item"><a class="page-link" href="?page=<?php echo $nextpage ?>"><?php echo $nextpage ?></a></li>
<li class="page-item">
<a class="page-link" href="?page=<?php echo $endpage ?>" aria-label="Next">
<span aria-hidden="true">»</span>
<span class="sr-only">Last</span>
</a>
</li>
<?php } ?>
</ul>
</nav>
<?php }?>
the data is correctly added into the database, but the problem is the pagination is nowhere seen in the page. when i just put the html it was coming,but when i added the php code inside it,its is not coming. can anyone tell me what could be the problem please?
Move <nav></nav> code inside
if(mysqli_num_rows($result) > 0){ }
Before or after your table.
Issue is that you now show it only if your if statement fails: if($result = mysqli_query($link, $sql)){ } else { }
Tip:
To Prevent SQL Injection i suggest:
PHP MySQLi Prepared Statements Tutorial
PHP PDO Prepared Statements Tutorial
There is a self-written website on WordPress tarifes. I made a script that searches for each copy of the thead table and makes it fixed to the fixed_table_header table, but here's the problem when the same shortcode makes a new table for each one and the same thead, help you figure out how to add or change the script so that the header was fixed for each table separately
<?php
/*====================================================SHORTCODES EXEL=========================================================*/
public function show_mps_excel($atts){
$atts = shortcode_atts( array(
'name' => 'express_import',
'sheet' => 0,
'class' => '',
), $atts );
extract($atts);
?>
<?php $mps_option = get_option('gamma_mps'); ?>
<?php if(isset($mps_option[$name]['sheet'.$sheet])): ?>
<?php ob_start(); ?>
<div class="container-fluid block-content">
<div class="row">
<div class="col-sm-12 col-md-12 col-lg-12 welcome-text">
<!-- <table class="table table-hover table-bordered taxes" style="margin-top: -25px"> -->
<?php if($name != 'zones'): ?>
<?php $this->full_table($mps_option, $name, $sheet, $class); ?>
<?php else: ?>
<?php $this->half_table($mps_option, $name, $sheet, $class, 0, 118); ?>
<?php $this->half_table($mps_option, $name, $sheet, $class, 117, 234); ?>
<?php endif; ?>
<?php if(false): ?>
<h5>Загрузить таблицу в .XLSX: <a class="btn btn-success" href="<?php echo $mps_option[$name]['download_url']; ?>">Загрузить</a></h5>
<?php endif; ?>
</div>
</div>
</div>
<?php $html = ob_get_clean(); ?>
<?php endif; ?>
<?php
return $html;
}
private function full_table($mps_option, $name, $sheet, $class){
?>
<table class="table table-hover table-bordered mps_xls sheet-<?php echo $sheet; ?> <?php echo $name; ?> <?php echo $class; ?>" style="margin-top: -25px">
<?php foreach ($mps_option[$name]['sheet'.$sheet] as $row => $cols): ?>
<?php if(!$cols['A'] && !$cols['B'] && !$cols['C']) continue; ?>
<?php echo $row==1 ? '<thead><tr>':'<tr>'; ?>
<?php foreach ($cols as $col): ?>
<?php echo $row==1 ? '<th>':'<td>'; ?>
<?php echo $col; ?>
<?php echo $row==1 ? '</th>':'</td>'; ?>
<?php endforeach; ?>
<?php echo $row==1 ? '</tr></thead>':'</tr>'; ?>
<?php endforeach; ?>
</tbody>
</table>
<?php
}
private function half_table($mps_option, $name, $sheet, $class, $start_row, $end_row){
$count = 1;
?>
<div class="col-sm-6 col-md-6 col-lg-6 welcome-text">
<table class="table table-hover table-bordered mps_xls sheet-<?php echo $sheet; ?> <?php echo $name; ?> <?php echo $class; ?>" style="margin-top: -25px">
<?php foreach ($mps_option[$name]['sheet'.$sheet] as $row => $cols): ?>
<?php if($count <= $start_row && $count > 1) {$count++; continue;} ?>
<?php if($count >= $end_row) break; ?>
<?php echo $row==1 ? '<thead><tr>':'<tr>'; ?>
<?php foreach ($cols as $col): ?>
<?php echo $row==1 ? '<th>':'<td>'; ?>
<?php echo $col; ?>
<?php echo $row==1 ? '</th>':'</td>'; ?>
<?php endforeach; ?>
<?php echo $row==1 ? '</tr></thead>':'</tr>'; ?>
<?php $count++; ?>
<?php endforeach; ?>
</tbody>
</table>
</div>
<?php
}
}
?>
(function($) {
$(document).ready(function() {
var table = $('table'),
thead = table.find('thead'),
fixed_thead,
fixed_table = $('<table />', {
'cellpadding': 5,
'cellspacing': 0,
'border': 1,
'id': 'fixed_table_header'
}),
fixed_table_wrapper = $('<div />', {
'height': 400,
'css': {
'overflow': 'auto'
}
});
table.before(fixed_table);
thead.find('td').each(function() {
$(this).css('width', $(this).width());
});
fixed_thead = thead.clone();
fixed_table.append(fixed_thead);
thead.hide();
table.wrap(fixed_table_wrapper);
// align the new table header with the original table
fixed_table.css('left', (fixed_table.offset().left - table.offset().left) * -1);
});
})(jQuery);
If I understand your question correctly, you target only the first table by using var table = $('table'),. You need to run the manipulation on each table so your code should look something like:
(function($) {
$(document).ready(function() {
$('table').each(function() {
var table = $(this),
thead = table.find('thead'),
fixed_thead,
fixed_table = $('<table />', {
'cellpadding': 5,
'cellspacing': 0,
'border': 1,
'id': 'fixed_table_header'
}),
fixed_table_wrapper = $('<div />', {
'height': 400,
'css': {
'overflow': 'auto'
}
});
table.before(fixed_table);
thead.find('td').each(function() {
$(this).css('width', $(this).width());
});
fixed_thead = thead.clone();
fixed_table.append(fixed_thead);
thead.hide();
table.wrap(fixed_table_wrapper);
// align the new table header with the original table
fixed_table.css('left', (fixed_table.offset().left - table.offset().left) * -1);
});
});
})(jQuery);
This case is similar to the way a jQuery plugin should be written and the solution is similar too: https://learn.jquery.com/plugins/basic-plugin-creation/#using-the-each-method
I want that update button should be in that field which I choose.But it appears only in first row and is updating for first row quantity field.
<form action="cart.php?action=update" method="post">
<table>
<tr>
<th colspan="2">ITEM</th>
<th>QUANTITY</th>
<th>PRICE</th>
<th>SUBTOTAL</th>
<th>REMOVE</th>
</tr>
<?php
$query = "select * from cart where customer_id='$user' ";
$result = mysqli_query($con,$query);$b = 0;$c = 0;
while($row = mysqli_fetch_array($result))
{
$productid = $row['product_id'];
$query2 = "select * from product where product_id='$productid'";
$result2 = mysqli_query($con,$query2);
while($row2=mysqli_fetch_array($result2))
{
?>
<tr>
<td rowspan="3"><img src="upload/<?php echo $row2['pimage']; ?>" height="50px" width="50px"></td>
<td rowspan="3"><?php echo $row2['pname']; ?></td>
<td rowspan="3">
<input tpe="text" name="newqty" value="<?php echo $qty = $row['quantity']; ?>" onkeypress="showsubmit()">
<input style="visibility:hidden;width:80px;border-radius:10px;background-color:green;border:none;padding:5px;color:white;" type="submit" name="sub1" id="sub1" value="UPDATE">
<input type="hidden" name="hidcartid" value="<?php echo $row['cart_id'] ?>"/>
<input type="hidden" name="hidproductid" value="<?php echo $row['product_id']; ?>"/>
<script>
function showsubmit()
{
document.getElementById("sub1").style.visibility = "visible";
}
</script>
</td>
<td>Price:<?php echo $sp = $row2['psellingprice']; ?></td>
<?php
$total = $sp * $qty;
?>
<td rowspan="3">
<?php
echo $t = $total;
$b = $b + $t;
?></td>
<td rowspan="3">REMOVE</td>
</tr>
<?php
$action = ( array_key_exists( 'action', $_REQUEST) ? $_REQUEST['action'] : "" );
if($action =="delete")
{
deletecart($_REQUEST['cid']);
}
if($action=="update")
{
echo "update function called";
updatecart();
echo "update function executed";
}
?>
<tr>
<td>Selling Price:<?php echo $p = $row2['pprice']; ?></td>
</tr>
<tr>
<td>You Saved:
<?php
$d = $row2['pdiscount'];
$s = ($p*$d)/100;
echo $q = $s * $qty;
$c = $c + $q;
?> rs.</td>
</tr>
<?php
}
}
?>
</table>
and cart2.php
<?php
function deletecart($cartid)
{
include 'connection.php';
$sql1="delete from cart where cart_id=$cartid";
$executequery = mysqli_query($con,$sql1);
header('location:cart.php');
}
function updatecart()
{
include 'connection.php';
$cartId = $_POST['hidcartid'];
$productId = $_POST['hidproductid'];
$newqty = $_POST['newqty'];
echo("inside update function");
// update product quantity
$sql = "UPDATE cart
SET quantity = $newqty
WHERE cart_id = $cartId";
mysqli_query($con,$sql);
header('location:cart.php');
}?>
For row onw everything is fine.But for row2 update button appears in row1 and not updating at all.
<input tpe="text" name="newqty" value="<?php echo $qty = $row['quantity']; ?>" onkeypress="showsubmit(<?php echo $row['cart_id'] ?>)">
<input style="visibility:hidden;width:80px;border-radius:10px;background-color:green;border:none;padding:5px;color:white;"
type="submit"
name="sub_<?php echo $row['cart_id'] ?>"
id="sub_<?php echo $row['cart_id'] ?>"
value="UPDATE">
<script>
function showsubmit(id)
{
document.getElementById("sub_"+id).style.visibility ="visible";
}
</script>
I'm trying add to cart using CodeIgniter and it is working fine but, when I want to do the same through ajax its getting some problem. Can you please look at my codes and tell me where do I get some mistakes? I'm confused how to use ajax to call the add function of the controller . What should I add or do in the ajax code to make this function work?
<html>
<head>
<title>Codeigniter cart class</title>
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<link href='http://fonts.googleapis.com/css?family=Raleway:500,600,700' rel='stylesheet' type='text/css'>
<link rel="stylesheet" type="text/css" href="<?php echo base_url(); ?>css/style.css">
<script type="text/javascript">
$(document).ready(function() {
$("#myform").submit(function(event) {
event.preventDefault();
var insert_data= $("#myform").serializeArray();
$.ajax({
url: "<?php echo base_url(); ?>" + "index.php/shopping/add",
type: "POST",
data: insert_data,
success: function(response)
{
if (response)
{
//window.location.replace("http://127.0.0.1/codeigniter_cart2/index.php/shopping");
window.location.href="http://127.0.0.1/codeigniter_cart2/index.php/shopping";
}
else{
alert('sorry');
}
}
});
});
});
</script>
</head>
<body>
<div id='content'>
<div class="row">
<div class="col-sm-5">
<h2 align="center">Items</h2>
<?php
?>
<table id="table" border="0" cellpadding="5px" cellspacing="1px">
<?php
foreach ($products as $product) {
$id = $product['serial'];
$name = $product['name'];
$price = $product['price'];
?>
<tr class="well">
<td style="padding-left:15px;"><?php echo $name; ?></td>
<td>
Rs. <?php echo $price; ?></td>
<?php
?>
<?php
echo form_open('',array('id' => 'myform'));
echo form_hidden('id', $id);
echo form_hidden('name', $name);
echo form_hidden('price', $price);
?> <!--</div>-->
<?php
$btn = array(
'class' => 'fg-button teal',
'value' => 'Add',
'name' => 'action',
'id' => 'add_button'
);
?>
<td>
<?php
// Submit Button.
echo form_submit($btn);
echo form_close();
?>
</td>
</tr>
<?php } ?>
</table>
</div>
<div class="col-sm-7">
<!-- <div id="cart" >-->
<h2 align="center">Items on Cart</h2>
<div>
<?php $cart_check = $this->cart->contents();
if(empty($cart_check)) {
echo 'To add products to your shopping cart click on "Add" Button';
} ?> </div>
<table id="table" border="0" cellpadding="5px" cellspacing="1px">
<?php
// All values of cart store in "$cart".
if ($cart = $this->cart->contents()): ?>
<tr id= "main_heading" class="well">
<td style="padding-left:15px;"><?>Name</td>
<td>Price(Rs)</td>
<td>Qty</td>
<td>Amount</td>
<td>Remove</td>
</tr>
<?php
// Create form and send all values in "shopping/update_cart" function.
echo form_open('shopping/update_cart');
$grand_total = 0;
$i = 1;
foreach ($cart as $item):
echo form_hidden('cart[' . $item['id'] . '][id]', $item['id']);
echo form_hidden('cart[' . $item['id'] . '][rowid]', $item['rowid']);
echo form_hidden('cart[' . $item['id'] . '][name]', $item['name']);
echo form_hidden('cart[' . $item['id'] . '][price]', $item['price']);
echo form_hidden('cart[' . $item['id'] . '][qty]', $item['qty']);
?>
<tr class="well">
<td style="padding-left:15px;">
<?php echo $item['name']; ?>
</td>
<td>
<?php echo number_format($item['price'], 2); ?>
</td>
<td>
<?php echo form_input('cart[' . $item['id'] . '][qty]', $item['qty'], ' type="number" max="99" min="1" value="1" style="width:50px;"'); ?>
</td>
<?php $grand_total = $grand_total + $item['subtotal']; ?>
<td>
Rs <?php echo number_format($item['subtotal'], 2) ?>
</td>
<td>
<?php
// cancle image.
$path = "<img src='http://127.0.0.1/codeigniter_cart2/images/cart_cross.jpg' width='25px' height='20px'>";
echo anchor('shopping/remove/' . $item['rowid'], $path); ?>
</td>
<?php endforeach; ?>
</tr>
<tr>
<td style="padding-left:30px;"><b>Order Total: Rs <?php
//Grand Total.
echo number_format($grand_total, 2); ?></b></td>
<td colspan="5" align="right"><input type="button" class ='fg-button teal' value="Clear cart" onclick="window.location = 'shopping/remove/all'">
<?php //submit button. ?>
<input type="submit" class ='fg-button teal' value="Update Cart">
<?php echo form_close(); ?>
</td>
</tr>
<?php endif; ?>
</table>
</div>
<!-- <div id="products_e" align="center">-->
<!--</div>-->
<!-- </div>-->
</div>
</div>
</body>
Now my controller:
<?php if (!defined('BASEPATH')) exit('No direct script access allowed');
class Shopping extends CI_Controller {
public function __construct()
{
parent::__construct();
//load model
$this->load->model('billing_model');
$this->load->library('cart');
}
public function index()
{
$data['products'] = $this->billing_model->get_all();
$this->load->view('shopping_views', $data);
}
function add()
{
$insert_data = array(
'id' => $this->input->post('id'),
'name' => $this->input->post('name'),
'price' => $this->input->post('price'),
'qty' => 1
);
$this->cart->insert($insert_data);
redirect('shopping');
return TRUE;
}
function remove($rowid) {
// Check rowid value.
if ($rowid==="all"){
// Destroy data which store in session.
$this->cart->destroy();
}else{
// Destroy selected rowid in session.
$data = array(
'rowid' => $rowid,
'qty' => 0
);
// Update cart data, after cancle.
$this->cart->update($data);
}
// This will show cancle data in cart.
redirect('shopping');
}
function update_cart(){
// Recieve post values,calcute them and update
$cart_info = $_POST['cart'] ;
foreach( $cart_info as $id => $cart)
{
$rowid = $cart['rowid'];
$price = $cart['price'];
$amount = $price * $cart['qty'];
$qty = $cart['qty'];
$data = array(
'rowid' => $rowid,
'price' => $price,
'amount' => $amount,
'qty' => $qty
);
$this->cart->update($data);
}
redirect('shopping');
}
}
How should I apply this code to ajax?
Thanks for the help.
it's not necessary to use "success:"
However if you want to check error or debug
1) press F12 on Browser to open Developer Mode
2) do action (add cart)
3) on tab "Network" find your ajax request and see your error
Modify your add() function as follows:
function add(){
$insert_data = array('k1' => 'v1', 'k2' => 'v2');
$success = $this->cart->insert($insert_data);
if($success){
$res = array('status' => 200, 'msg' => 'success', 'somekey' => 'somevalue');
}else{
$res = array('status' => 500, 'msg' => 'database err');
}
echo json_encode($res);
}
Now the add() function has responded the ajax request with some json-formated data, you can parse the response data in javascript. The (success:) function should be like this:
function(response) {
if (response){
var res = JSON.parse(response);
if(res.status == 200){
window.location.href="http://127.0.0.1/codeigniter_cart2/index.php/shopping";
}else{
//error handler
alert(res.msg);
}
}else{
alert('sorry');
}
});
function __construct(){
parent::__construct();
$this->load->library(array('session','cart'));
$this->load->library('');
$this->load->helper('url');
$this->load->database();
}
public function product_list(){
$this->db->select('*');
$this->db->from('product');
$this->db->order_by('product_id','desc');
$rs = $this->db->get();
return $rs->result_array();
}
public function product_byId($pid){
$this->db->select('*');
$this->db->from('product');
$this->db->where('product_id',$pid);
$rs = $this->db->get();
return $rs->row_array();
}
Download full code from here http://phpcooker.com/codeigniter-shopping-cart
I have a button within a php foreach statement which loads a modal. How can i pass the particular id ($animalid) to the modal? I have it kind of working but the modal will load the same id in each modal popup. See my php foreach code below and also part of the modal.
$pdo2 = Database::connect();
$sql2 = 'SELECT * FROM animals WHERE riderid = '.$data[id].' AND hp != "Choose One"';
foreach ($pdo2->query($sql2) as $row) {
echo '<tr>';
echo '<td>'. $row['hp'] . '</td>';
echo '<td>'. $row['hpname'] . '</td>';
echo '<td>'. $row['hpage'] . '</td>';
echo '<td>'. $row['hpcolour'] . '</td>';
echo '<td>'. $row['hpmicro'] . '</td>';
echo '<td>';
echo '<button class="btn btn-default btn-xs" id="float-right" data-toggle="modal" data-target=".bs-example-modal-lg-2"><span class="glyphicon glyphicon-pencil"></span> Update</button>';
echo ' ';
echo '<a class="btn btn-default btn-xs" href="#"><span class="glyphicon glyphicon-trash"></span> Delete</a>';
echo '</td>';
echo '</tr>';
$animalid = $row['id'];
}
Database::disconnect();
?>
Modal Code
<div class="modal-body">
<form name="editanimal" id="editanimal" class="form-horizontal" action="updateanimal.php" method="post">
<span class="form-break">
<?php
// Get Animal id
//$animalid = $data['id'];
echo $animalid;
?>
$animalid is in the loop. If you want to use that value, you can store the data to other array and use it. Hope you get some inspiration.
PHP:
<?php
$pdo2 = Database::connect();
$sql2 = 'SELECT * FROM animals WHERE riderid = '.$data[id].' AND hp != "Choose One"';
$list = array();
foreach ($pdo2->query($sql2) as $row) {
$item = array();
$content = '<tr>';
$content .= '<td>'. $row['hp'] . '</td>';
$content .= '<td>'. $row['hpname'] . '</td>';
$content .= '<td>'. $row['hpage'] . '</td>';
$content .= '<td>'. $row['hpcolour'] . '</td>';
$content .= '<td>'. $row['hpmicro'] . '</td>';
$content .= '<td>';
$content .= '<button class="btn btn-default btn-xs" id="float-right" data-toggle="modal" data-target=".bs-example-modal-lg-2"><span class="glyphicon glyphicon-pencil"></span> Update</button>';
$content .= ' ';
$content .= '<a class="btn btn-default btn-xs" href="#"><span class="glyphicon glyphicon-trash"></span> Delete</a>';
$content .= '</td>';
$content .= '</tr>';
$item['id'] = $row['id'];
$item['content'] = $content;
$list[] = $item;
}
Database::disconnect();
?>
HTML:
<div class="modal-body">
<form name="editanimal" id="editanimal" class="form-horizontal" action="updateanimal.php" method="post">
<span class="form-break"></span>
<?php foreach($list as $item){ ?>
<?php echo $item['id'];?>
<?php } ?>
or..
<table>
<?php foreach($list as $item){ ?>
<?php echo $item['content'];?>
<?php } ?>
</table>
<!-- ... -->
</form>
</div>
$animalid is being over written each time you iterate through the foreach loop. You would have to build an array to hold all of the animalids, and pass that to your modal or print out the id as you are iterating through the loop.