how to write javascript which create fixedheader for each table separately - javascript

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

Related

Change cell background depending on mysql field value

I have the following code and my MySQL table has a column (not showing) called ativo. I need the $result_rowset['Nome'][$i] = $row['nome']; to have background-color changed to red if ativo = 0 and blue if ativo = 1.
Can anyone help me on this? I've tried so many ways found here but I couldn't customize anyone to my case.
Thanks in advance.
<?php
$result_rowset = array();
$i = 0 ;
while( $row = mysqli_fetch_array($result)) {
$result_rowset['Nome'][$i] = $row['nome'];
$result_rowset['Campo 01'][$i] = $row['campo1'];
$result_rowset['Campo 02'][$i] = $row['campo2'];
$result_rowset['Campo 03'][$i] = $row['campo3'];
$result_rowset['Campo 04'][$i] = $row['campo4'];
$result_rowset['Campo 05'][$i] = $row['campo5'];
$i ++ ;
}
$result->data_seek(0);
?>
<section class="feature-area section-gap" style="padding-top: 10px;">
<div class="container">
<div class="row d-flex justify-content-center" style="max-width: 1240px;">
<div class="mytable table-responsive">
<table class="table table-striped table-bordered table-hover">
<tbody>
<?php foreach ( $result_rowset as $result_key => $result_value ) { ?>
<tr>
<td><?php echo $result_key ; ?></td>
<?php foreach ( $result_value as $val ) { ?>
<td><?php echo $val ; ?></td>
<?php } ?>
</tr>
<?php } ?>
</tbody>
</table>
</div>
</div>
</div>
</section>
First u need still save the column ativo when you fetch array
<?php
$result_rowset = array();
$i = 0 ;
while( $row = mysqli_fetch_array($result)) {
$result_rowset['Nome'][$i] = $row['nome'];
$result_rowset['ativo'][$i] = $row['ativo'];
$i ++ ;
}
$result->data_seek(0);
?>
and when you foreach the array you can add condition to make background color changed depends on column ativo
<table class="table table-striped table-bordered table-hover">
<tbody>
<?php foreach ( $result_rowset as $r ) { ?>
<tr>
<?php if($r->ativo==0){ ?>
<td style="background-color:red">
<?php }elseif($r->ativo==1){ ?>
<td style="background-color:blue">
<?php }else{ ?>
<td>
<?php } ?>
<?php echo $r->nome; ?>
</td>
</tr>
<?php } ?>
</tbody>
</table>

Wordpress button in wo-xml feed administration not working

Problem is in administration console of wordpress in plugin 'woocommerce xml feeds'. There is button to add parameter for category. This button do nothing when I click it.
I tried to contact the author of plugin, he only told me to check debug console, but there is nothing. He also told me that function of this button depends on jQuery.
This is the button element:
<span class="btn btn-danger btn-sm add-param" data-par="80">Přidat parametr</span>
The whole PHP file for context:
<?php
/**
*
* #package woo_xml_feeds
* #author Vladislav Musilek
* #license GPL-2.0+
* #link http://musilda.cz
* #copyright 2014 Vladislav Musilek
*
* Version 1.0.0
*
*/
if(isset($_POST['update'])){
//Save Heureka.sk Shipping values
$this->save_heureka_delivery($name = 'woo_heureka_delivery');
//Save Heureka.cz CPC value
$this->save_single_option('heureka-cpc','heureka-cpc');
/**
* Save Heureka category
*/
$heureka_assing_categories = get_option('woo_heureka_assing_categories');
if(empty($heureka_assing_categories)){ $heureka_assing_categories = array(); }
$heureka_excluded_categories = get_option( 'woo_heureka_excluded_categories');
if(empty($heureka_excluded_categories)){ $heureka_excluded_categories = array(); }
$heureka_categories_cpc = get_option( 'woo_heureka_categories_cpc');
if(empty($heureka_categories_cpc)){ $heureka_categories_cpc = array(); }
foreach($_POST['termid'] as $key => $item){
if(!empty($_POST['heurekaid'])){
if(!empty($_POST['heurekaid'][$key])){
$heureka_assing_categories[$_POST['termid'][$key]] = $_POST['heurekaid'][$key];
}else{
if(!empty($heureka_assing_categories[$_POST['termid'][$key]])){
unset($heureka_assing_categories[$_POST['termid'][$key]]);
}
}
}
if(!empty($_POST['excluded'][$key])){
$heureka_excluded_categories[$_POST['termid'][$key]] = $_POST['termid'][$key];
}else{
if(!empty($heureka_excluded_categories[$_POST['termid'][$key]])){
unset($heureka_excluded_categories[$_POST['termid'][$key]]);
}
}
if(!empty($_POST['termvar'][$key])){
$heureka_categories_cpc[$_POST['termid'][$key]] = $_POST['category_cpc'][$key];
}else{
if(!empty($heureka_categories_cpc[$_POST['termid'][$key]])){
unset($heureka_categories_cpc[$_POST['termid'][$key]]);
}
}
}
update_option( 'woo_heureka_assing_categories', $heureka_assing_categories );
update_option( 'woo_heureka_excluded_categories', $heureka_excluded_categories );
update_option( 'woo_heureka_categories_cpc', $heureka_categories_cpc );
//Parametry pro kategorie
$cat_params = get_option( 'woo_heureka_cat_params');
if(empty($cat_params)){ $cat_params = array(); }
foreach($_POST['termvar'] as $key => $item){
$cat_params[$item]['term_id'] = $item;
$cat_params[$item]['parametry'] = array();
if(!empty($_POST['nazev_parametru_'.$item])){
foreach($_POST['nazev_parametru_'.$item] as $lit => $var){
$cat_params[$item]['parametry'][$lit]['nazev_parametru'] = $_POST['nazev_parametru_'.$item][$lit];
$cat_params[$item]['parametry'][$lit]['hodnota_parametru'] = $_POST['hodnota_parametru_'.$item][$lit];
}
}
}
update_option( 'woo_heureka_cat_params', $cat_params );
if(isset($_GET['catoffset'])){
wp_redirect(admin_url().'admin.php?page=heureka-cz&catoffset='.$_GET['catoffset']);
}else{
wp_redirect(admin_url().'admin.php?page=heureka-cz');
}
}
$cat_params = get_option( 'woo_heureka_cat_params');
//Get heureka cz categories
$heureka_categories = get_option( 'woo_heureka_categories');
$heureka_assing_categories = get_option( 'woo_heureka_assing_categories');
$heureka_excluded_categories = get_option( 'woo_heureka_excluded_categories');
$heureka_categories_cpc = get_option( 'woo_heureka_categories_cpc');
$catTerms = get_terms('product_cat', array('hide_empty' => 0, 'orderby' => 'ASC'));
$cat_list = custom_taxonomy_walker('product_cat');
$use_select2 = get_option( 'woo_xml_feed_use_select2' );
/**
* Cat pagging
*
*/
$limit = 50;
if(isset($_GET['catoffset'])){
$catstart = (($_GET['catoffset'] * $limit) - $limit)+1;
$catend = $_GET['catoffset'] * $limit;
}else{
$catstart = 1;
$catend = $limit;
}
$i = 1;
$ii = 1;
?>
<div class="wrap">
<h2><?php echo esc_html( get_admin_page_title() ); ?></h2>
<form method="post" action="">
<?php
//Include Heureka CPC table
include('modules/heureka_cz_cpc.php');
//Include Heureka Shipping table
include('modules/heureka_cz_shipping.php');
//Display category setting paggination
echo tax_pagination($cat_list, 50);
?>
<!-- Heureka kategorie -->
<div class="t-col-12">
<div class="toret-box box-info">
<div class="box-header">
<h3 class="box-title"><?php _e('Přiřazení kategorií','woo-xml-feeds'); ?></h3>
</div>
<div class="box-body">
<p><?php _e('Zde můžete přiřadit všechny kategorie ve vašem obchodu, k jednotlivým kategoriím Heuréky. Pokud máte v eshopu větší množství kategorií, buďte prosím trpěliví, načtení může chvíli trvat. Po rozkliknutí výběru Heuréka kategorie, můžete do řádku zapsat počáteční písmena hledané kategorie a použít našeptávač.','woo-xml-feeds'); ?></p>
<p><?php _e('Pokud nechcete zobrazovat zboží z určité kategorie v XML feedu, zaškrtněte "Vyloučit kategorii".','woo-xml-feeds'); ?></p>
<table class="table-bordered">
<tr>
<th><?php _e('Vyloučit kategorii', 'woo-xml-feeds'); ?></th>
<th><?php _e('Kategorie obchodu', 'woo-xml-feeds'); ?></th>
<th><?php _e('Kategorie na Heuréce', 'woo-xml-feeds'); ?></th>
<th><?php _e('CPC kategorie', 'woo-xml-feeds'); ?></th>
</tr>
<?php
$catTerms = explode(',',$cat_list);
$aa = 0;
foreach($catTerms as $c_item) :
if(!empty($c_item) && $i >= $catstart){
if($i > $catend){ break; }
?>
<tr>
<td class="td_center"><input class="icheck_red" type="checkbox" name="excluded[<?php echo $aa; ?>]" <?php if(!empty($heureka_excluded_categories[$c_item])){ echo 'checked="checked"'; } ?> value="<?php echo $c_item; ?>" ></td>
<td>
<?php
$aa++;
$catTerm = get_term_by( 'id', $c_item, 'product_cat' );
if(!empty($catTerm->parent)){
$p_name = get_term_by( 'id', $catTerm->parent, 'product_cat' );
echo $p_name->name.' >> ';
}
?> <?php echo $catTerm->name; ?>
<input type="hidden" name="termid[]" value="<?php echo $catTerm->term_id; ?>" />
</td>
<td>
<?php
if(!empty($use_select2) && $use_select2 == 'no'){}else{
?>
<script>
jQuery(document).ready(function() { jQuery("#heureka<?php echo $i; ?>").select2(); });
</script>
<?php } ?>
<style>#s2id_heureka<?php echo $i; ?>{min-width:800px;}</style>
<select name="heurekaid[]" id="heureka<?php echo $i; ?>">
<option value="default"></option>
<?php
foreach($heureka_categories as $key => $item){
if(!empty($item['category_fullname'])){
?>
<option <?php if(!empty($heureka_assing_categories[$catTerm->term_id]) && $heureka_assing_categories[$catTerm->term_id]==$key){ echo 'selected="selected"'; }; ?>value="<?php echo $key; ?>"><?php echo $item['category_fullname']; ?></option>
<?php }
}
?>
</select>
</td>
<td><input type="text" name="category_cpc[]" value="<?php if(!empty($heureka_categories_cpc[$c_item])){ echo $heureka_categories_cpc[$c_item]; } ?>" style="width:40px;" /></td>
</tr>
<?php
}
$i++;
endforeach;
?>
</table>
</div>
</div>
</div>
<!-- Heureka kategorie parametry -->
<div class="t-col-12">
<div class="toret-box box-info">
<div class="box-header">
<h3 class="box-title"><?php _e('Vlastní parametry pro kategorie','woo-xml-feeds'); ?></h3>
</div>
<div class="box-body">
<table class="table-bordered">
<tr>
<th><?php _e('Kategorie eshop', 'woo-xml-feeds'); ?></th>
<th style="width:80%;"><?php _e('Vlastní parametry', 'woo-xml-feeds'); ?></th>
</tr>
<?php
$catTerms = explode(',',$cat_list);
foreach($catTerms as $c_item) :
if(!empty($c_item) && $ii >= $catstart){
if($ii > $catend){ break; }
?>
<tr>
<td>
<?php
$catTerm = get_term_by( 'id', $c_item, 'product_cat' );
if(!empty($catTerm->parent)){
$p_name = get_term_by( 'id', $catTerm->parent, 'product_cat' );
echo $p_name->name.' >> ';
}
?> <?php echo $catTerm->name; ?>
<input type="hidden" name="termvar[<?php echo $catTerm->term_id; ?>]" value="<?php echo $catTerm->term_id; ?>" />
</td>
<td class="category_params">
<?php
if(!empty($cat_params[$catTerm->term_id]['parametry'])){
foreach($cat_params[$catTerm->term_id]['parametry'] as $lit => $var){ ?>
<fieldset>
<input type="text" name="nazev_parametru_<?php echo $catTerm->term_id; ?>[]" placeholder="Název parametru" value="<?php echo $var['nazev_parametru']; ?>" />
<input type="text" name="hodnota_parametru_<?php echo $catTerm->term_id; ?>[]" placeholder="Hodnota parametru" value="<?php echo $var['hodnota_parametru']; ?>"/>
<span class="btn btn-danger btn-sm remove-param"><i class="fa fa-times"></i></span>
</fieldset>
<?php }
}
?>
<div class="clear"></div>
<span class="btn btn-danger btn-sm add-param"data-par="<?php echo $catTerm->term_id; ?>">Přidat parametr</span>
</td>
</tr>
<?php
}
$ii++;
endforeach;
?>
</table>
<input type="hidden" name="update" value="ok" />
<input type="submit" class="btn btn-lg btn-warning" value="<?php _e('Uložit nastavení','woo-xml-feeds'); ?>" />
</div>
</div>
</div>
</form>
</div>
I really tried to google it I found similar problems with some simple advice to switch to default theme or to put define('CONCATENATE_SCRIPTS', false); to wp-config.php. No luck with any of these.

Add to cart with ajax in codeigniter

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

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