shopping cart in codeigniter using ajax - ajax

Hi I am new with ajax and having problem. I am trying to make a shopping cart using ajax.I don't know what is wrong with my code please help me out.
When I click the add button an alert comes 'No success' and nothing happen , I am not able add items to cart.
Thanks for helping me.
This is my view
<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= $(this).serializeArray();
$.ajax({
url: "<?php echo base_url(); ?>" + "index.php/shopping2/add",
dataType: 'json',
//type: "POST",
data: insert_data,
success:function(response) {
//if (response){
//var res = JSON.parse(response);
var res = response;
if(res.status == 200){
window.location.href="http://127.0.0.1/codeigniter_cart2/index.php/shopping2";
}else{
alert(res.msg);
}
//}
//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()): ?>
<div id="addcart">
<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('shopping2/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" id="addcart">
<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 = 'shopping2/remove'">
<?php //submit button. ?>
<input type="submit" class ='fg-button teal' value="Update Cart">
<?php echo form_close(); ?>
</td>
</tr></div>
<?php endif; ?>
</table>
</div>
<!-- <div id="products_e" align="center">-->
<!--</div>-->
<!-- </div>-->
</div>
</div>
</body>
</html>
This is my controller
<?php if (!defined('BASEPATH')) exit('No direct script access allowed');
class Shopping2 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_view2', $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);
//$success = $this->cart->insert($insert_data);
$cart_check = $this->cart->contents();
if(!empty($cart_check)){
//$this->cart->contents(insert_data);
$res = array('status' => 200, 'msg' => 'success');
}else{
$res = array('status' => 500, 'msg' => 'No success');
}
echo json_encode($res);
//echo $data[0]['value'];
//redirect('shopping2');
}
function remove($rowid) {
// Check rowid value.
if ($rowid==="all"){
$this->cart->destroy();
}else{
$data = array(
'rowid' => $rowid,
'qty' => 0
);
$this->cart->update($data);
}
redirect('shopping2');
}
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('shopping2');
}
}
Please help me how to add items in the cart using ajax.

Since u managed to get a response, the problem should lie in your Model or data insertion.
Few suggestions:
It's also recommended that you use $.post() instead of $.ajax().
"<?php echo base_url(); ?>" + "index.php/shopping2/add" can be changed to "<?php echo site_url('shopping2/add"'); ?>"
Use the built in Codeignter output class to output your JSON. See here: https://www.codeigniter.com/userguide3/libraries/output.html

Related

datewise searching not working in pagination

My search result correctly displaying. But when I click the second page or pagination then all the data is displaying
my view - date selecting
Here I select the date using the date picker
<div class='floatl modal-form col-sm-12'>
<div class='col-sm-5'>
<input type='text' class='dateTablePicker' readonly id='dateTableFrom'
placeholder='date from'/>
</div>
<div class='col-sm-5'>
<input type='text' class='dateTablePicker' readonly id='dateTableTo'
placeholder='date to'/>
</div>
<div class='col-sm-2'>
<button class='btn-success' onclick="filterTable()"> Filter</button>
</div>
</div>
<div class='contentTable'>
<?php
$this->load->view("pages/tableData/leads_data");
?>
</div>
<script>
$(function () {
$(".dateTablePicker").datepicker({dateFormat: 'yy-mm-dd'});
});
function filterTable() {
$.ajax({
type: "POST",
url: "<?= site_url('OperationRouter/filterTableData'); ?>",
data: {dateTableFrom: $('#dateTableFrom').val(), dateTableTo: $('#dateTableTo').val()},
success: function (data) {
$(".contentTable").html(data);
}
});
}
leads_data//table data listing
The data displaying if the datefrom and dateto is isset then data displaying based on searching.
<?php
if (!isset($_SESSION['dateTableFrom'])) $_SESSION['dateTableFrom'] = '';
if (!isset($_SESSION['dateTableTo'])) $_SESSION['dateTableTo'] = '';
$dateTableFrom = $_SESSION['dateTableFrom'];
$dateTableTo = $_SESSION['dateTableTo'];
$page='leads';
$slno = 0;
// CONDITION QUERY
if (isset($_SESSION['export_Sql']))
$cql = $_SESSION['export_Sql'];
else if($dateTableFrom) {
$cql = '
select leads.id,leads.created,leads.product_id,
leads.company_id,leads.owner_id,leads.creator_id,
leads.title,leads.date,products.title as product,
leads.converted_flag,leads.status,
companies.title as company,admin.username
from admin admin,products products,leads leads,companies
companies
where products.id=leads.product_id
and companies.id=leads.company_id
and admin.id=leads.owner_id
and leads.remove_status = 1
and
( leads.creator_id = ' . $this->session-
>userdata['logged_admin'] . '
or FIND_IN_SET(leads.creator_id, ( select
GROUP_CONCAT(id) from admin
where parent_id =' . $this->session-
>userdata['logged_admin'] . ' ))
)
and STR_TO_DATE(leads.created,"%d-%m-%Y") >= "' . $dateTableFrom . '"
and
STR_TO_DATE(leads.created,"%d-%m-%Y") <= "' . $dateTableTo . '"
';
}
else
{
$cql = '
select leads.id,leads.created,leads.product_id,
leads.company_id,leads.owner_id,leads.creator_id,
leads.title,leads.date,products.title as product,
leads.converted_flag,leads.status,
companies.title as company,admin.username
from admin admin,products products,leads leads,companies
companies
where products.id=leads.product_id
and companies.id=leads.company_id
and admin.id=leads.owner_id
and leads.remove_status = 1
and
( leads.creator_id = ' . $this->session-
>userdata['logged_admin'] . '
or FIND_IN_SET(leads.creator_id, ( select
GROUP_CONCAT(id) from admin
where parent_id =' . $this->session-
>userdata['logged_admin'] . ' ))
)
';
}
if (isset($_SESSION['export_Ids']) && $_SESSION['export_Ids']) {
$cql .= " and leads.id in (" . $_SESSION['export_Ids'] . ") ";
}
if (isset($_SESSION['export_Order']) &&
$_SESSION['export_Order'])
$oql = $_SESSION['export_Order'];
else
$oql = ''; // ORDER QUERY
if (isset($_SESSION['export_Limit']))
$lql = $_SESSION['export_Limit'];
else
$lql='';
if (isset($_SESSION['export_Ids']) && $_SESSION['export_Ids']) // IF ID'S
THEN NO EXPORT LIMIT NEEDED
$lql = '';
$sql = $cql . $oql;
$itemcount = $this->OperationModel->getRowCount($sql);
$sql = $cql . $oql . $lql;
?>
<input type='hidden' id='selectedSql' value='<?= $cql ?>'/>
<input type='hidden' id='selectedOrder' value='<?= $oql ?>'/>
<input type='hidden' id='selectedLimit' value='<?= $lql ?>'/>
<?php
$slno = 0;
//$sql='select * from admin_types where remove_status = 1';
$tableArray['searchFields'] = 'leads.title';
$itemsperpage = 6;
$result = $this->OperationModel->getTableData($sql,
$tableArray['searchFields'], $itemsperpage);
if (isset($result['data'])) {
$admin_det = $this->Adminuser->getsingleadmin($this->session-
>userdata['logged_admin']);
?>
<div class='custom-data-table '>
<table class='customtable'>
<tr>
<th style='width:70px;' class='checker'>
<input type='checkbox' class='thCheckbox'/>
<div class='customCheckbox'></div>
</th>
<th style='width:60px;'> No</th>
<th style='width:230px;'>
Title
<div class='floatr'><i class='i-sorter icon-shuffle'
data='leads.title'
title='sort records by title'></i>
</div>
</th>
<th>
Date
<div class='floatr'><i class='i-sorter icon-shuffle'
data='leads.created'
title='sort records by date '></i>
</div>
</th>
<th>
Service
<div class='floatr'><i class='i-sorter icon-shuffle'
data='products.title'
title='sort records by date '></i>
</div>
</th>
<th>
Client
<div class='floatr'><i class='i-sorter icon-shuffle'
data='companies.title'
title='sort records by company'>
</i></div>
</th>
<th>
Owner
<div class='floatr'><i class='i-sorter icon-shuffle'
data='admin.username'
title='sort records by owner'></i></div>
</th>
<?php if ($page != 'excelexport') { ?>
<?php if ($admin_det[0]['user_type'] == 'admin' ||
$admin_det[0]['user_type'] == 2) { ?>
<th> Conversion
<div class='floatr'><i class='i-sorter icon-
shuffle' data='leads.converted_flag'
title='sort records by
conversion status'></i></div>
</th>
<?php } ?>
<!--
<th>
Status
</th>
!-->
<th> Actions</th>
<?php } ?>
</tr>
<?php
// $slno=intval($current_page);
if (isset($searchkey)) $searchkey = $searchkey; else $searchkey
= '**';
foreach ($result['data'] as $row) {
$slno++;
?>
<tr id='<?= $row['id'] ?>'>
<td>
<input type='checkbox' class='tdCheckbox'/>
<div id='<?= $row['id'] ?>' class='customCheckbox'>
</div>
</td>
<td> <?= $slno ?> </td>
<td><?= $this->OperationModel-
>searchKeyCheck($row['title'], $searchkey) ?></td>
<td><?= $row['created'] ?></td>
<td><?= $this->OperationModel-
>searchKeyCheck($row['product'], $searchkey) ?></td>
<td><?= $this->OperationModel-
>searchKeyCheck($row['company'], $searchkey) ?></td>
<td><?= $this->OperationModel-
>searchKeyCheck($row['username'], $searchkey) ?></td>
<!--
<td><?= $row['lead_status'] ? '<span
style="color:green">Active</span>' : '<span
style="color:orange">Inactive</span>' ?></td>
!-->
<?php if ($page != 'excelexport') { ?>
<?php if ($admin_det[0]['user_type'] == 'admin' ||
$admin_det[0]['user_type'] == 2) { ?>
<td>
<button class='status-button'
data-trigger='leads'
data-value='<?=
$row['converted_flag'] ?>'
data-raw='<?= $row['id'] ?>'
data-field='converted_flag'
data-success="<span
class='colorange'>DisConvert</span>"
data-failure="<span
class='colgreen'>Convert</span>">
<?= ($row['converted_flag'] == 1) ? "
<span class='colorange'>DisConvert</span>" : "<span
class='colgreen'>Convert</span>" ?>
</button>
</td>
<?php } ?>
<td>
<?php
if ($row['creator_id'] ==
$_SESSION['logged_admin'] || $admin_det[0]['user_type'] ==
'admin' || $admin_det[0]['user_type'] == 2) { ?>
<a class='modal-switch'
data-toggle='modal'
data-target='#getAppUsers'
data-ajax='createmeeting'>
<i class='fa fa-plus add-bt'></i>
Meeting
</a>
<a class='modal-switch'
data-toggle='modal'
data-target='#getAppUsers'
data-ajax='createlead' data-raw='<?=
$row['id'] ?>'>
<i class='fa fa-pencil ed-bt'></i>
</a>
<?php if ($admin_det[0]['user_type'] ==
'admin') { ?>
<a class='delete-trigger' data-
trigger='leads' data-raw='<?= $row['id'] ?>'>
<i class='fa fa-trash del-bt'></i>
</a>
<?php } ?>
<?php } ?>
<a class='modal-switch'
data-toggle='modal'
data-operation='view'
data-target='#getAppUsers'
data-ajax='createlead' data-raw='<?=
$row['id'] ?>'>
<i class='fa fa-eye ed-bt'></i>
</a>
</td>
<?php } ?>
</tr>
<?php
}
?>
</table>
</div>
<?php
/* THE PAGINATION PART */
$pagination['base_url'] = $page;
$pagination['itemsperpage'] = $itemsperpage;
$pagination['total_rows'] = $this->OperationModel->getRowCount($sql,
$tableArray['searchFields']);
/* THE PAGINATION PART */
if (isset($pagination))
echo $this->OperationModel->getPagination($pagination);
?>
<?php
} else {
echo " <span class='floatl no-match-span'> <i class='icon-magnifier'></i>
<span>Oopz , No data found in database for the corresponding item .
</span> </span> ";
}
?>
<?php
$this->session->unset_userdata('dateTableFrom');
?>
pagination part
Here is the pagination part
function getPagination($dataArray = '')
{
$msg = '';
if ($dataArray) {
$this->load->library('pagination');
$config['base_url'] = base_url() . $dataArray['base_url'];
//$config['base_url'] = base_url('controller_name/search');
$config['uri_segment'] = 2;
$config['total_rows'] = $dataArray['total_rows'];
$config['per_page'] = $dataArray['itemsperpage'];
$this->pagination->initialize($config);
$msg .= "<div class='pagination'>";
$msg .= $this->pagination->create_links();
$msg .= "</div>";
return $msg;
} else
return false;
}
You should pass the search params (filters) along with the ajax request. (along with the pagination)

Ajax data retrieve from controller

Hi i have called the database value in codeigniter controller and computed the values of database and stored in one new variable. So how can i get both the database values and the new variable that I have created in the controller as I want to display all database value and the new computed value in view. Please suggest me.
My controller: welcome
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Welcome extends CI_Controller {
public $total;
public function __construct() {
parent::__construct();
$this->load->library('table');
$this->load->model('product_database');
}
public function index() {
$data['show_table'] = $this->view_table();
$this->load->view('welcome_message', $data);
}
public function view_table(){
$result = $this->product_database->show_all_data();
if ($result != false) {
return $result;
} else {
return 'Database is empty !';
}
}
public function AddtoCart(){
$id = $this->input->post('product_id');
$qty = $this->input->post('qty');
$this->db->where('id', $id); // Select where id matches the posted id
$query = $this->db->get('productlist', 1); // Select the products where a match is found and limit the query by 1
foreach ($query->result() as $row)
{
$data = array(
'id' => $id,
'qty' => $qty,
'price' => $row->price,
'name' => $row->name
);
$total=$qty*$row->price;
echo $total;
}
}
}
?>
my view: welcome_message
<!DOCTYPE HTML>
<html>
<head>
<title>Product list</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<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.12.0/jquery.min.js"> </script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"> </script>
<script type="text/javascript">
$(document).ready(function() {
$("#add").click(function(event) {
event.preventDefault();
jQuery.ajax({
type: "POST",
url: "<?php echo base_url(); ?>" + "index.php/Welcome/AddtoCart",
dataType: 'json',
data: {name: },
success: function(res) {
if (res)
{ alert();
// Show Entered Value
jQuery("#total").html(res.total);
}
}
});
});
});
</script>
</head>
<body>
<div class="container">
<div class="message">
<?php
if (isset($read_set_value)) {
echo $read_set_value;
}
if (isset($message_display)) {
echo $message_display;
}
?>
</div>
<div> <?php
if (isset($show_table)) {
echo "<div class='productlist'>";
if ($show_table == 'Database is empty !') {
echo $show_table;
} else {
echo '<h2>Product List</h2><br/><br/>';
?>
<div class="row">
<div class="col-sm-8">
<div class="well">
<div class="table-responsive">
<?php
echo "<table width='98%', >";
echo '<tr><th class="e_id">Id</th><th>ProductName</th> <th>Price</th> <tr/>';
$i=1;
foreach ($show_table as $value) {
?>
<tr class="well" >
<?php
echo "<td width='30%' height='27px'>" . $value->id . "</td>" . "<td width='70%' height='27px'>" . $value->name . "</td>" . "<td height='27px'>" . $value->price . "</td>";
?>
<?php echo form_open('/Welcome/AddtoCart'); ?>
<td><input type="number" name="qty" value="1" style="width:40px;" min="1" max="99"></td>
<input type="hidden" name="product_id" value="<?php echo $value->id ?>" />
<td><input type="submit" value="Add" id="add" width="100%"></td>
<td><input type="submit" value="Rmv" id="rmv" width="100%"></td></br>
<?php echo form_close(); ?>
</tr>
<?php
$i=$i+1;}
echo '</table>';
?>
</div>
</div>
</div>
<div class="col-sm-4">
<div class="well">
<h4>Cart</h4>
Total Rs:<input type="text" value="" id="total"></br><br>
<input type="submit" value="Checkout" id="chk_out">
</div>
</div>
</div>
<?php
}
echo "</div>";
}
?>
</div>
</div>
</body>
</html>
And my model
<?php
if (!defined('BASEPATH'))
exit('No direct script access allowed');
class Product_database extends CI_Model {
public function show_all_data() {
$this->db->select('*');
$this->db->from('productlist');
$query = $this->db->get();
if ($query->num_rows() > 0) {
return $query->result();
} else {
return false;
}
}
}
?>
In place of echo $total you can put this code :
$total= array('total'=> $total);
$youarray=array_merge($data, $total);
echo json_econde($youarray,true);

form validation with array not working

On my form I have some check boxes. And they are in an array. When I submit my form for some reason it clears the Modify check boxes. And then when go back to look not checked.
I have know what's causing issue is $this->form_validation->set_rules('permission[modify]', '', 'callback_modify_check_edit')
It does not seem to like, permission[modify] or permission[modify][] on the set_rules
How am I able to solve this?
Controller Edit Function:
public function edit() {
$this->load->library('form_validation');
$this->form_validation->set_rules('name', 'User Group Name', 'required');
$this->form_validation->set_rules('user_group_id', 'User Group Id', 'required');
$this->form_validation->set_rules('permission[modify]', '', 'callback_modify_check_edit');
if ($this->form_validation->run($this) == FALSE) {
$this->getForm();
} else {
$this->load->model('admin/user/model_user_group');
$this->model_user_group->editUserGroup($this->uri->segment(4), $this->input->post());
$this->db->select('permission');
$this->db->from($this->db->dbprefix . 'user_group');
$this->db->where('user_group_id', $this->session->userdata('user_group_id'));
$user_group_query = $this->db->get();
$permissions = unserialize($user_group_query->row('permission'));
$this->session->set_userdata($permissions);
$this->session->set_flashdata('success', 'Congratulations you have successfully modified' .' '. "<strong>" . ucwords(str_replace('_', ' ', $this->router->fetch_class())) .' '. $this->input->post('name') . "</strong>");
redirect('admin/users_group');
}
}
public function modify_check_edit() {
if (!in_array('users_group', $this->session->userdata('modify'))) {
$this->form_validation->set_message('modify_check_edit', 'You do not have permission to edit' );
}
}
View Form:
<?php echo validation_errors('<div class="alert alert-warning text-center"><i class="fa fa-exclamation-triangle"></i>
', '</div>'); ?>
<?php if ($this->uri->segment(4) == FALSE) { ?>
<?php $data = array('class' => 'form-horizontal', 'id' => 'users_group');?>
<?php echo form_open('admin/users_group/add', $data);?>
<?php } else { ?>
<?php $data = array('class' => 'form-horizontal', 'id' => 'users_group');?>
<?php echo form_open('admin/users_group/edit' .'/'. $this->uri->segment(4), $data);?>
<?php } ?>
<div class="form-group">
<?php $data = array('class' => 'col-sm-2 control-label');?>
<?php echo form_label('User Group Name', 'name', $data);?>
<div class="col-sm-10">
<?php
$data_user_name = array(
'id' => 'name',
'name' => 'name',
'class' => 'form-control',
'value' => $name
)
;?>
<?php echo form_input($data_user_name);?>
</div>
</div>
<div class="form-group">
<?php $data = array('class' => 'col-sm-2 control-label');?>
<?php echo form_label('User Group Id', 'user_group_id', $data);?>
<div class="col-sm-10">
<?php
$data_user_group_id = array(
'id' => 'user_group_id',
'name' => 'user_group_id',
'class' => 'form-control',
'value' => $user_group_id
)
;?>
<?php echo form_input($data_user_group_id);?>
</div>
</div>
<div class="form-group">
<?php $data = array('class' => 'col-sm-2 control-label');?>
<?php echo form_label('Access Permission', 'permission_access', $data);?>
<div class="col-sm-10">
<div class="well well-sm" style="height: 200px; overflow: auto;">
<?php foreach ($permissions as $permission) { ?>
<div class="checkbox">
<label>
<?php if (in_array($permission, $access)) { ?>
<?php
$data_checked = array(
'name' => 'permission[access][]',
'id' => 'permission_access',
'value' => $permission,
'checked' => TRUE,
);
echo form_checkbox($data_checked);
?>
<?php echo $permission; ?>
<?php } else { ?>
<?php
$data_not_checked = array(
'name' => 'permission[access][]',
'id' => 'permission_access',
'value' => $permission,
'checked' => FALSE,
);
echo form_checkbox($data_not_checked);
?>
<?php echo $permission; ?>
<?php } ?>
</label>
</div>
<?php } ?>
</div>
<a onclick="$(this).parent().find(':checkbox').prop('checked', true);">Select All</a> / <a onclick="$(this).parent().find(':checkbox').prop('checked', false);">Unselect All</a></div>
</div>
<div class="form-group">
<?php $data = array('class' => 'col-sm-2 control-label');?>
<?php echo form_label('Modify Permission', 'permission_modify', $data);?>
<div class="col-sm-10">
<div class="well well-sm" style="height: 200px; overflow: auto;">
<?php foreach ($permissions as $permission) { ?>
<div class="checkbox">
<label>
<?php if (in_array($permission, $modify)) { ?>
<?php
$data = array(
'name' => 'permission[modify][]',
'id' => 'permission_modify',
'value' => $permission,
'checked' => TRUE,
);
echo form_checkbox($data);
?>
<?php echo $permission; ?>
<?php } else { ?>
<?php
$data = array(
'name' => 'permission[modify][]',
'id' => 'permission_modify',
'value' => $permission,
'checked' => FALSE,
);
echo form_checkbox($data);
?>
<?php echo $permission; ?>
<?php } ?>
</label>
</div>
<?php } ?>
</div>
<a onclick="$(this).parent().find(':checkbox').prop('checked', true);">Select All</a> / <a onclick="$(this).parent().find(':checkbox').prop('checked', false);">Unselect All</a></div>
</div>
<?php echo form_close();?>
After a good half hour trying to figure it out it was mostly part of the call back not to working with th set_rules() for permission[modify]
Just fixed code here for call back and seems to be working now.
public function modify_check_edit() {
$this->load->library('form_validation');
if (is_array($this->session->userdata('modify'))) {
$permission = !in_array('users_group', $this->session->userdata('modify'));
if ($permission) {
$this->form_validation->set_message('modify_check_edit', 'You do not have permission to one' .' '. "<strong>" . ucwords(str_replace('_', ' ', $this->router->fetch_class())) .' '. $this->input->post('name') . "</strong>");
return FALSE;
} else {
return TRUE;
}
return TRUE;
} else {
$this->form_validation->set_message('modify_check_edit', 'You do not have permission to one' .' '. "<strong>" . ucwords(str_replace('_', ' ', $this->router->fetch_class())) .' '. $this->input->post('name') . "</strong>");
return FALSE;
}
}

$variable with site_url codeigniter

I would like to know if it is possible to get a $variable id mixed in with the codeigniter.
Currently just shows http://localhost/codeigniter/codeigniter-cms/0
I just need it to display http://localhost/codeigniter/codeigniter-cms/admin/setting with id hidden and still access this controller.
But If create new website it has different ID so different settings.
foreach ($results as $result) {
$data['websites'][] = array(
'website_id' => $result->website_id,
'name' => $result->name,
'url' => $result->url,
'edit' => site_url('admin/setting') . $result->website_id
);
}
View
<?php if ($websites) { ?>
<?php foreach($websites as $website) { ?>
<tr>
<td class="text-center"><?php if (in_array($website['website_id'], $selected)) { ?>
<input type="checkbox" name="selected[]" value="<?php echo $website['website_id']; ?>" checked="checked" />
<?php } else { ?>
<input type="checkbox" name="selected[]" value="<?php echo $website['website_id']; ?>" />
<?php } ?></td>
<td><?php echo $website['name'];?></td>
<td><?php echo $website['url'];?> </td>
<td class="text-right"><i class="fa fa-pencil"></i> Edit Website</td>
</tr>
<?php } ?>
<?php } else { ?>
<tr>
<td class="text-center" colspan="4">NO RESULTS</td>
</tr>
<?php } ?>
I can view link now changed edit on controller and made on model result_array instead of result. link working fine.
'edit' => site_url('admin/setting', $result['website_id'])
controller updated
$results = $this->model_website->getWebsites();
foreach ($results as $result) {
$data['websites'][] = array(
'website_id' => $result['website_id'],
'name' => $result['name'],
'url' => $result['url'],
'edit' => site_url('admin/setting', $result['website_id'])
);
}
model updated
function getWebsites() {
$this->db->order_by('url', 'asc');
$query = $this->db->get('website');
if($query->num_rows() > 0) {
return $query->result_array();
} else {
return false;
}
}

Magento - Controller to Ajax Estimate Shipping: Load Block and display phtml

I copied estimatePostAction and made estimateAjaxPostAction (overriding core - I did not hack the core). The controller action works as well (class Mage_Checkout_CartController).
Now I want to get/create a block for replacing shipping block after estimate shipping with ajax. I tried this:
public function estimateAjaxPostAction()
{
$country = (string) $this->getRequest()->getParam('country_id');
$postcode = (string) $this->getRequest()->getParam('estimate_postcode');
$city = (string) $this->getRequest()->getParam('estimate_city');
$regionId = (string) $this->getRequest()->getParam('region_id');
$region = (string) $this->getRequest()->getParam('region');
$this->_getQuote()->getShippingAddress()
->setCountryId($country)
->setCity($city)
->setPostcode($postcode)
->setRegionId($regionId)
->setRegion($region)
->setCollectShippingRates(true);
$this->_getQuote()->save();
//$this->_goBack();
$this->loadLayout();
$block = $this->getLayout()->createBlock('Mage_Checkout_Block_Cart_Shipping','checkout.cart.shipping.ajax',array('template' => 'checkout/cart/shipping.phtml'));
if($block) {
$response = array();
$response['shipping'] = $block->toHtml();
$this->getResponse()->setBody(Mage::helper('core')->jsonEncode($response));
}
}
The block checkout.cart.shipping.ajax was created. But toHtml() returns nothing.
My JSON returns:
{"shipping":""}
Why toHtml method doesn't work?
Edit: My block code (checkout/cart/shipping.phtml)
<?php /** #var $this Mage_Checkout_Block_Cart_Shipping */ ?>
<div class="row contem-shipping">
<div class="col-xs-10 shipping">
<div class="text-ship">
<h2><?php echo $this->__('Calcular o frete:') ?></h2>
<p><?php echo $this->__('Insira o CEP do endereço<br />no campo ao lado.') ?></p>
</div>
<div class="shipping-form">
<form action="<?php echo $this->getUrl('checkout/cart/estimatePost') ?>" method="post" id="shipping-zip-form">
<ul class="form-list">
<li class="no-display">
<div class="input-box">
<?php echo Mage::getBlockSingleton('directory/data')->getCountryHtmlSelect($this->getEstimateCountryId()) ?>
</div>
</li>
<?php if($this->getStateActive()): ?>
<li>
<label for="region_id"<?php if ($this->isStateProvinceRequired()) echo ' class="required"' ?>><?php if ($this->isStateProvinceRequired()) echo '<em>*</em>' ?><?php echo $this->__('State/Province') ?></label>
<div class="input-box">
<select id="region_id" name="region_id" title="<?php echo $this->__('State/Province') ?>" style="display:none;"<?php echo ($this->isStateProvinceRequired() ? ' class="validate-select"' : '') ?>>
<option value=""><?php echo $this->__('Please select region, state or province') ?></option>
</select>
<script type="text/javascript">
//<![CDATA[
$('region_id').setAttribute('defaultValue', "<?php echo $this->getEstimateRegionId() ?>");
//]]>
</script>
<input type="text" id="region" name="region" value="<?php echo $this->escapeHtml($this->getEstimateRegion()) ?>" title="<?php echo $this->__('State/Province') ?>" class="input-text" style="display:none;" />
</div>
</li>
<?php endif; ?>
<?php if($this->getCityActive()): ?>
<li>
<label for="city"<?php if ($this->isCityRequired()) echo ' class="required"' ?>><?php if ($this->isCityRequired()) echo '<em>*</em>' ?><?php echo $this->__('City') ?></label>
<div class="input-box">
<input class="input-text<?php if ($this->isCityRequired()):?> required-entry<?php endif;?>" id="city" type="text" name="estimate_city" value="<?php echo $this->escapeHtml($this->getEstimateCity()) ?>" />
</div>
</li>
<?php endif; ?>
<li>
<div class="input-box">
<input class="input-text validate-postcode<?php if ($this->isZipCodeRequired()):?> required-entry<?php endif;?>" type="text" id="postcode" name="estimate_postcode" value="<?php echo $this->escapeHtml($this->getEstimatePostcode()) ?>" />
</div>
</li>
</ul>
<div class="buttons-set">
<button id="button-cep" style="width: 100px;" type="button" title="<?php echo $this->__('Get a Quote') ?>" onclick="calculaFreteAjax(jQuery('#postcode').val()); return false;" class="btn btn-2 btn-2a"><?php echo $this->__('Get a Quote') ?></button>
</div>
</form>
<script type="text/javascript">
//<![CDATA[
new RegionUpdater('country', 'region', 'region_id', <?php echo $this->helper('directory')->getRegionJson() ?>);
//]]>
</script>
<?php $_shippingRateGroups = $this->getEstimateRates(); ?>
<?php if ($_shippingRateGroups): ?>
<form id="co-shipping-method-form" action="<?php echo $this->getUrl('checkout/cart/estimateUpdatePost') ?>">
<dl class="sp-methods">
<?php foreach ($_shippingRateGroups as $code => $_rates): ?>
<dt><?php echo $this->escapeHtml($this->getCarrierName($code)) ?></dt>
<dd>
<ul>
<?php foreach ($_rates as $_rate): ?>
<li<?php if ($_rate->getErrorMessage()) echo ' class="error-msg"';?>>
<?php if ($_rate->getErrorMessage()): ?>
<?php echo $this->escapeHtml($_rate->getErrorMessage()) ?>
<?php else: ?>
<input name="estimate_method" type="radio" value="<?php echo $this->escapeHtml($_rate->getCode()) ?>" id="s_method_<?php echo $_rate->getCode() ?>"<?php if($_rate->getCode()===$this->getAddressShippingMethod()) echo ' checked="checked"' ?> class="radio" />
<label for="s_method_<?php echo $_rate->getCode() ?>"><?php echo $this->escapeHtml($_rate->getMethodTitle()) ?>
<?php $_excl = $this->getShippingPrice($_rate->getPrice(), $this->helper('tax')->displayShippingPriceIncludingTax()); ?>
<?php $_incl = $this->getShippingPrice($_rate->getPrice(), true); ?>
<?php echo $_excl; ?>
<?php if ($this->helper('tax')->displayShippingBothPrices() && $_incl != $_excl): ?>
(<?php echo $this->__('Incl. Tax'); ?> <?php echo $_incl; ?>)
<?php endif; ?>
</label>
<?php endif ?>
</li>
<?php endforeach; ?>
</ul>
</dd>
<?php endforeach; ?>
</dl>
</form>
<?php endif; ?>
<script type="text/javascript">
//<![CDATA[
var coShippingMethodForm = new VarienForm('shipping-zip-form');
var countriesWithOptionalZip = <?php echo $this->helper('directory')->getCountriesWithOptionalZip(true) ?>;
coShippingMethodForm.submit = function () {
var country = $F('country');
var optionalZip = false;
for (i=0; i < countriesWithOptionalZip.length; i++) {
if (countriesWithOptionalZip[i] == country) {
optionalZip = true;
}
}
if (optionalZip) {
$('postcode').removeClassName('required-entry');
}
else {
$('postcode').addClassName('required-entry');
}
return VarienForm.prototype.submit.bind(coShippingMethodForm)();
}
//]]>
</script>
</div>
</div>
<div class="col-xs-6">
<?php
$totalItemsInCart = Mage::helper('checkout/cart')->getItemsCount(); //total items in cart
$totals = Mage::getSingleton('checkout/session')->getQuote()->getTotals(); //Total object
$subtotal = $totals["subtotal"]->getValue(); //Subtotal value
$grandtotal = $totals["grand_total"]->getValue(); //Grandtotal value
if(isset($totals['discount']) && $totals['discount']->getValue()) {
$discount = $totals['discount']->getValue(); //Discount value if applied
} else {
$discount = '';
}
$shipping = Mage::helper('checkout')->getQuote()->getShippingAddress()->getData();
$tax = $shipping["shipping_amount"];
/*if( $totals["tax"]->getValue()) {
$tax = $totals["tax"]->getValue(); //Tax value if present
} else {
$tax = '';
}*/
?>
<table class="totals-cart">
<tr>
<td class="total-tile">
Subtotal do pedido:
</td>
<td class="total-price">
<?php echo Mage::helper('core')->currency($subtotal, true, false); ?>
</td>
</tr>
<tr>
<td class="total-tile">
Frete:
</td>
<td class="total-price">
<?php echo Mage::helper('core')->currency($tax, true, false); ?>
</td>
</tr>
<?php if ($discount):?>
<tr>
<td class="total-tile">
Desconto:
</td>
<td class="total-price">
<?php echo Mage::helper('core')->currency($discount, true, false); ?>
</td>
</tr>
<?php endif;?>
</table>
</div>
</div>
<div class="row">
<div class="col-xs-16">
<div class="grand-total">
<p class="text">Total:</p>
<p class="price"><?php echo Mage::helper('core')->currency($grandtotal, true, false);?></p>
</div>
</div>
</div>
<script type="text/javascript">
function calculaFreteAjax(cep) {
jQuery('.contem-shipping .shipping').html('<span class="remove-frete" style="display: block; margin: 0 auto; width: 20px;" id="login-please-wait"><img src="http://sites.xpd.com.br/cpaps/skin/frontend/xpd/default/images/opc-ajax-loader.gif" class="v-middle" alt=""/></span>');
var param = {'country_id': 'BR','estimate_postcode': cep};
console.log(param);
jQuery.ajax({
type: "GET",
url: '<?php echo Mage::getBaseUrl().'checkout/cart/estimateAjaxPost/'; ?>', //My Custom Controller
data: param,
success: function(response) {
response = jQuery.parseJSON(response);
if(response.shipping) {
jQuery('.contem-shipping').parent().html(response.shipping);
}
else {
alert('Falha ao calcular o frete. Tente novamente.');
}
}
});
jQuery('#co-shipping-method-form dd input.radio').click(function(){
//I will submit the shipping method selected
});
}
</script>
Denis... I have modify code please check
public function estimateAjaxPostAction()
{
$country = (string) $this->getRequest()->getParam('country_id');
$postcode = (string) $this->getRequest()->getParam('estimate_postcode');
$city = (string) $this->getRequest()->getParam('estimate_city');
$regionId = (string) $this->getRequest()->getParam('region_id');
$region = (string) $this->getRequest()->getParam('region');
$this->_getQuote()->getShippingAddress()
->setCountryId($country)
->setCity($city)
->setPostcode($postcode)
->setRegionId($regionId)
->setRegion($region)
->setCollectShippingRates(true);
$this->_getQuote()->save();
$response = array();
$response['shipping']=$this->eastmatesajax();
$this->getResponse()->setBody(Mage::helper('core')->jsonEncode($response));
}
protected function eastmatesajax()
{
$layout=$this->getLayout();
$layout->getMessagesBlock()->setMessages(Mage::getSingleton('checkout/session')->getMessages(true),Mage::getSingleton('catalog/session')->getMessages(true));
$block = $this->getLayout()->createBlock('checkout/cart_shipping')->setTemplate( 'checkout/cart/shipping.phtml');
return $block->toHtml();
}
Updated block issue solved using $this->_getQuote()->collectTotals(); before $this->_getQuote()->save();

Resources