Add to cart with ajax in codeigniter - javascript

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

Related

how to write javascript which create fixedheader for each table separately

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 to pass data in codeigniter from view using ajax post, process that data in controller and send back the result array to view

I have searched the whole WWW but get nothing helpful. Any Solution will be appreciated. thanks in advance
MY HTML
<div class="row">
Either the form tag needed in my case or not
<form>
<div class="form-group">
<label for="date" class="col-12 col-md-2 control-label"><?php echo 'Date';?>
</label>
<div class="col-12 col-md-3">
<input type="text" class="datepicker form-control" name="date" id="date">
</div>
</div>
Here I am getting the data from my database
<div class="form-group">
<label for="class_id" class="col-12 col-md-2 control-label"><?php echo
get_phrase('Select Class');?></label>
<div class="col-12 col-md-3">
<select name="class_id" class="form-control" id="class_id" onchange="return get_attendance()" >
<option value=""><?php echo get_phrase('select class');?></option>
<?php
$classes = $this->db->get('class')->result_array();
foreach($classes as $row):?>
<option value="<?php echo $row['class_id'];?>"><?php echo $row['name'];?></option>
<?php endforeach; ?>
</select>
</div>
</div>
</form>
</div>
I am using datatable class for exporting and printing
<table class="table table-bordered datatable" id="table_export">
<thead>
<tr>
<th>#</th>
<th><div><?php echo get_phrase('Status');?></div></th>
<th><div><?php echo get_phrase('Student Name');?></div></th>
<th><div><?php echo get_phrase('Class Name');?></div></th>
<th><div><?php echo get_phrase('Date');?></div></th>
<th><div><?php echo get_phrase('options');?></div></th>
</tr>
</thead>
<tbody>
<?php
$count = 1;
foreach($attendance as $row):?>
$attendance is recieved from the controller in $this->load->view('backend/index', $page_data);
<tr>
<td><?php echo $count++;?></td>
<td><?php echo $row['status'];?></td>
<td><?php echo $row['student_id'];?></td>
<td><?php echo $row['class_id'];?></td>
<td><?php echo $row['date'];?></td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
MY JavaScript
The script below alert() the class_id and date but do not pass anything to the controller function
<script type="text/javascript">
function get_attendance() {
var class_id = $('#class_id').val();
var date = $('#date').val();
$.ajax({
type: "post",
dataType:"json",
data: {"class_id": class_id, "date": date},
url: '<?php echo base_url();?>index.php?admin/manage_attendance',
success: function (data) {
}
});
}
</script>
My Controller
If I give static value to $date and $class_id as $date = '04-04-2018'; $class_id = 2; inside manage_attendance() below it works but using $this->input->post() do nothing:
function manage_attendance()
{
if($this->session->userdata('admin_login')!=1)
redirect(base_url() , 'refresh');
$date = $this->input->post('date');
$class_id = $this->input->post('class_id');
$page_data['attendance']= $this->db->get_where('attendance', array('class_id' => $class_id , 'date' => $date))->result_array();
$page_data['page_name'] = 'manage_attendance';
$page_data['page_title'] = get_phrase('manage_daily_attendance');
$this->load->view('backend/index', $page_data);
}
Try to change
url: '<?php echo base_url();?>index.php?admin/manage_attendance'
to
url: '<?php echo base_url();?>index.php/admin/manage_attendance',
You have to append data like this using jquery:
function get_attendance() {
var class_id = $('#class_id').val();
var date = $('#date').val();
$.ajax({
type: "post",
dataType:"json",
data: {class_id: class_id, date: date},
url: '<?php echo base_url();?>index.php?admin/manage_attendance',
success: function (data) {
var resultData = JSON.parse(response);
if(resultData!=null){
attendance= resultData.length;
}
if(attendance>0){
for(i=0;i<attendance;i++){
$(".attendance_listing").append("<tr><td>"+resultData[i].status+"</td><td>"+resultData[i].student_id+"</td><td>"+resultData[i].class_id+"</td><td>"+resultData[i].date+"</td></tr>");
}
}
}
});
}
//controler
function manage_attendance()
{
if($this->session->userdata('admin_login')!=1){
redirect(base_url() , 'refresh');
$date = $this->input->post('date');
$class_id = $this->input->post('class_id');
$page_data['attendance']= $this->db->get_where('attendance', array('class_id' => $class_id , 'date' => $date))->result_array();
$page_data['page_name'] = 'manage_attendance';
$page_data['page_title'] = get_phrase('manage_daily_attendance');
echo json_encode($page_data);
}
}
I can get the same result by coding as following but I do not prefer that method/logic I want something as I have posted above
HTML
<div class="form-group">
<label for="class_id" class="col-12 col-md-2 control-label"><?php echo
get_phrase('Select Class');?></label>
<div class="col-12 col-md-3">
<select name="class_id" class="form-control" id="class_id" onchange="return get_attendance()" >
<option value=""><?php echo get_phrase('select class');?></option>
<?php
$classes = $this->db->get('class')->result_array();
foreach($classes as $row):?>
<option value="<?php echo $row['class_id'];?>"><?php echo $row['name'];?></option>
<?php endforeach; ?>
</select>
</div>
</div>
</form>
</div>
<table class="table table-bordered datatable" id="table_export">
<thead>
<tr>
<th>#</th>
<th><div><?php echo get_phrase('Status');?></div></th>
<th><div><?php echo get_phrase('Student Name');?></div></th>
<th><div><?php echo get_phrase('Class Name');?></div></th>
<th><div><?php echo get_phrase('Date');?></div></th>
</tr>
</thead>
<tbody id="putdatahere">
</tbody>
</table>
JavaScript
<script type="text/javascript">
function get_attendance() {
var e = document.getElementById("class_id");
var class_id = e[e.selectedIndex].value;
var date = $('#date').val();
$.ajax({
url: '<?php echo base_url();?>index.php?admin/manage_attendance/'+ date +'/' + class_id,
success: function(response)
{
jQuery('#putdatahere').html(response);
}
});
}
</script>
CodeIgniter Controller
function manage_attendance($date, $class_id){
$query = $this->db->get_where('attendance', array('class_id' => $class_id , 'date' => $date))->result_array();
if($query){
$html_return = "";
foreach ($query as $attendance) {
$html_return .="<tr><td>";
$html_return .= $attendance['status']; //further Proccessing here e.g if $attendance['status'] == 0 echo absent otherwise present
$html_return .="</td><td>";
$html_return .= $attendance['student_id']); //further Proccessing here e.g get student name from its student_id
$html_return .="</td><td>";
$html_return .= $attendance['class_id']; //further Proccessing here e.g get class name from its class_id
$html_return .= "</td><td>";
$html_return .= $attendance['date'];
$html_return .="</td></tr>";
}
echo $html_return;
} else {
echo 'No record';
}
}

Best way to select multiple selections seperatly from foreach output

I have this foreach loop:
foreach ($userItems_get as $item => $value) {
if ($value['prefab'] == 'wearable') {
echo $value['name'] . "</br>";
echo "<img src=\"{$value['image_inventory']}.png\" width=\"90\" height=\"60\">" . "</br>";
if (!isset($value['item_rarity'])) {
$rarity = "common";
} else {
$rarity = $value['item_rarity'];
}
echo $rarity . "</br>";
foreach ($userItemsLoad as $key => $values) {
if ($item == $values['defindex']) {
echo $values['id'] . "</br></br>";
break;
}
}
}
}
which outputs the data in this format:
http://puu.sh/kVTjk/c1471e903a.jpg
I want the user to select which item he wants to trade/use and i want to recieve the ID of that item which is the integer value at the bottom, the user should be able to select multiple items?
How do i accomplish this? and whats the best way to do this? Thanks.
There are lot of ways of achieving this.
You can use normal Submit:
<form method="POST" action="script.php">
<table>
<tr>
<th></th>
<th>Image</th>
<th>Name</th>
</tr>
<?php
foreach ($userItems_get as $item => $value) {
if ($value['prefab'] == 'wearable') {
$id = "";
foreach ($userItemsLoad as $key => $values) {
if ($item == $values['defindex']) {
$id = $values['id'];
break;
}
}
?>
<tr>
<td><input type="checkbox" name="itemSelect[]" class="itemSelect" value="<?php echo $id; ?>" /></td>
<td>
<img src="<?php echo $value['image_inventory']; ?>.png" width="90" height="60">
</td>
<td>
<?php echo $value['name']; ?><br />
<?php
if (!isset($value['item_rarity'])) {
$rarity = "common";
} else {
$rarity = $value['item_rarity'];
}
?>
</td>
</tr>
<?php
}
}
?>
</table>
<button type="Submit">
Normal Submit
</button>
<button type="button" id="ajSubmit">
Ajax Submit
</button>
</form>
Script.php:
<?php
echo "<pre>";
print_r($_POST['itemSelect']);
echo "</pre>";
?>
Or Use jQuery:
<script>
$(function() {
$("#ajSubmit").click(function() {
var selectedItemIds = $("input.itemSelect").map(function(){
return $(this).val();
}).get();
});
});
</script>
The selectedItemIds will hold all the ID values.
Add a checkbox for each items, and add a class for the checkboxes for referencing
<input class="itemId" type="checkbox" value="$values['defindex']">
You can use JQuery to select all the checked checkboxes and loop then in a each loop
//Select all input elements which has class of itemId and it is checked then loop through with each.
$("input.itemId[checked='checked']").each(function(){
var itemId = $(this).val();
alert(itemId);
//Do something else
}

Javascript print function

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?

Cart is updated only once using Jquery and Codeigniter

I am working on Updating Codeigntier Cart with Jquery using Ajax call to update. Here is my jquery function
$(function() {
$('.cart_form select').on('change', function(ev) {
var rowid = $(this).attr('class');
var qty = $(this).val();
var postData_updatecart = {
'rowid' : rowid,
'qty' : qty
};
//posting data to update cart
$.ajax({
url : base_url + 'bookings/update_booking_cart',
type : 'post',
data : postData_updatecart,
beforeSend : function() {
$('#cart_content').html('Updating...');
},
success : function(html) {
//window.location.href = "postproperty.php?type="+suffix+'&page=page1';
$('#cart_content').html(html);
}
});
});
});
I have cart view file as
<div class="cart_form">
<?php echo form_open(base_url().'index.php/bookings/customerdetails', array('class' => 'bookings_form_customer', 'id' => 'bookings_form_customer')); ?>
<table cellpadding="6" cellspacing="1" style="width:100%" border="0">
<tr>
<th style="text-align:left">Item Description</th>
<th style="text-align:left">QTY</th>
<th style="text-align:right">Item Price</th>
<th style="text-align:right">Sub-Total</th>
</tr>
<?php $i = 1; ?>
<?php foreach ($this->cart->contents() as $items): ?>
<?php echo form_hidden($i.'[rowid]', $items['rowid']); ?>
<tr>
<td>
<?php echo $items['name']; ?>
<?php if ($this->cart->has_options($items['rowid']) == TRUE): ?>
<p>
<?php foreach ($this->cart->product_options($items['rowid']) as $option_name => $option_value): ?>
<strong><?php echo $option_name; ?>:</strong> <?php echo $option_value; ?><br />
<?php endforeach; ?>
</p>
<?php endif; ?>
</td>
<td>
<select name="<?php echo $i.'[qty]'; ?>" class="<?php echo $items['rowid']; ?>">
<?php
for($tt=0; $tt<=10; $tt++)
{
?>
<option value="<?php echo $tt; ?>" <?php if($tt==$items['qty']) echo 'selected="selected"'; ?>><?php echo $tt; ?></option>
<?php
}
?>
</select>
</td>
<td style="text-align:right"><?php echo $this->cart->format_number($items['price']); ?></td>
<td style="text-align:right">$<?php echo $this->cart->format_number($items['subtotal']); ?></td>
</tr>
<?php $i++; ?>
<?php endforeach; ?>
<tr>
<td colspan="2"> </td>
<td class="right"><strong>Total</strong></td>
<td class="right">$<?php echo $this->cart->format_number($this->cart->total()); ?></td>
</tr>
</table>
<p><?php echo form_submit('update_cart', 'Update your Cart'); ?></p>
</form>
</div>
Things are working Nice. But, lets say if I have 2 products, if i select one item's qty from 1 to 2, cart is updated and updated cart is shown using AJAX. But, if I immediately change another item's qty then it doesnt work.
The cart view file is inside class 'cart_form'.
Helping hands are appreciated.
I got an answer. You can refer below link
Ajax Request works only once
OR
Directly follow this
REPLACE jquery code part by
$(function() {
$(document).on( "change", "#bookings_form_customer select", function(ev) {
// your code goes here
});
});

Categories