Change active to inactive using buttons realtime - javascript

I am using DataTables with ajax using PHP CodeIgniter Framework. I am having a problem with switching Active buttons to Inactive buttons, vice versa.
What I want is:
When I click Active button, It should change to Inactive in realtime without refreshing the page.
Controller:
function activateStatus() {
$id = $this->uri->segment(3);
$data = array(
'status' => 1
);
$this->equip_model->updateAccount('equip', $data, array('id' =>$id));
}
function deactivateStatus() {
$id = $this->uri->segment(3);
$data = array(
'status' => 0
);
$this->equip_model->updateAccount('equip', $data, array('id' =>$id));
}
View:
<table class="table table table-hover table-bordered" id="equipmain">
<thead>
<tr>
<th>ID</th>
<th>Status</th>
</tr>
</thead>
<tbody>
<?php
foreach ($equip as $row){
?>
<tr>
<td style="display: none;"><?= $row->id ?></td>
<td align="center">
<?php
$status = $row->status;
if($status == "1") { ?>
<button id="<?php echo $row->id ?>" class="btn btn-xs green-jungle statusupdate1">&#10003</button>
<?php } else { ?>
<button id="<?php echo $row->id ?>" class="btn btn-xs red-flamingo statusupdate0" >&#10005</button>
<?php } ?>
</td>
</tr>
</tbody>
</table>
AJAX:
var oTable = $('#equipmain').DataTable( {
"searching": false,
"processing":true,
"columnWidth": 20,
"serverSide": true,
"autoWidth": true,
});
$(document).on('click', '.statusupdate0', function() {
var id = $(this).attr("id");
$.ajax({
url: "<?= base_url() ?>Admin/activateStatus/" + id,
success: function (data) {
oTable.ajax.reload();
}
});
});
$(document).on('click', '.statusupdate1', function() {
var id = $(this).attr("id");
$.ajax({
url: "<?= base_url() ?>Admin/deactivateStatus/" + id,
success: function (data) {
oTable.ajax.reload();
}
});
});
I don't know where is the error why the buttons are not working.

It may be that you are missing the semicolon (;) after your base_url() call. In the AJAX section for both buttons, try changing <?= base_url() ?> to <?= base_url(); ?> and see if that solves the issue.

Related

How to redirecting page to another page using ajax jquery in codeigniter?

am using codeigniter, am working shopping cart. after selecting of items to cart using ajax jquery. Here, items menu and cart table will be side by side displayed.
Now, my task is to copying cart items to another table, by clicking button,which is done. now problem is on clicking button i need to copied and at a time i need to route to another page.. here i can copy cart items to another table but i can't redirect to another.for this i used jquery ajax.
now i need route to page which in views folder users/basket.php
Home.php
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
?>
<div class="row">
<div class="col-lg-12 text-center">
<?php if(isset($_SESSION['loggedin'])){?>
<div class="alert alert-success"><?php echo $_SESSION['loggedin'];?></div>
<?php } ?>
Hello, <?php echo $_SESSION['username']?>
</div>
</div>
<div class="row">
<div class="col-lg-3">
<table class="table table-condensed table-hover">
<tr>
<th class="text-center">Item</th>
<th class="text-center">Quantity</th>
<th class="text-center">Price</th>
<th class="text-center">Add</th>
</tr>
<?php foreach($items as $item):?>
<tr class="success">
<td><?php echo $item['product_name'];?></td>
<td class="text-center"><input type="text" name="quantity" id="<?php echo $item['product_id'];?>" class="quantity" maxlength="2" size="2"></td>
<td><?php echo $item['product_price'];?></td>
<td><button type="button" name="add_cart" class="add_cart" data-productname="<?php echo $item['product_name'];?>" data-price="<?php echo $item['product_price'];?>" data-productid="<?php echo $item['product_id'];?>"><i class="fa fa-plus-circle"></i></button></td>
</tr>
<?php endforeach; ?>
</table>
</div>
<div class="col-lg-6 col-lg-offset-1">
<div id="cart_details" class="text-center">
</div>
</div>
</div>
Product_controller.php:
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Products extends CI_Controller {
public function add(){
$this->load->library('cart');
$data = array(
'id' => $_POST["product_id"],
'name' => $_POST["product_name"],
'qty' => $_POST["quantity"],
'price' => $_POST["product_price"],
);
$this->cart->insert($data); //return rowid
echo $this->view();
}
public function load(){
echo $this->view();
}
public function remove(){
$this->load->library('cart');
$row_id = $_POST["row_id"];
$data = array(
'rowid' => $row_id,
'qty' => 0
);
$this->cart->update($data);
echo $this->view();
}
public function clear(){
$this->load->library('cart');
$this->cart->destroy();
echo $this->view();
}
public function view(){
$this->load->library('cart');
$output = '';
$output.='
<h3>Shopping cart</h3><br/>
<div class="table-responsive">
<div align="right">
<button type="button" id="clear_cart" class="btn btn-danger"><i class="fa fa-trash-o" aria-hidden="true"></i></button>
</div>
<br/>
<table class="table table-bordered">
<tr>
<th class="text-center">Name</th>
<th class="text-center">Quantity</th>
<th class="text-center">Price</th>
<th class="text-center">Total</th>
<th class="text-center">Action</th>
</tr>';
$count = 0;
$content=$this->cart->contents();
foreach($content as $items){
$count++;
$output .='
<tr>
<td>'.$items["name"].'</td>
<td>'.$items["qty"].'</td>
<td>'.$items["price"].'</td>
<td>'.$items["subtotal"].'</td>
<td><button type="button" name="remove" class="btn btn-danger btn-xs remove_inventory" id="'.$items["rowid"].'"><i class="fa fa-times" aria-hidden="true"></i></button></td>
</tr>';
}
$output .='
<tr>
<td colspan="4" align="right">Total</td>
<td>'.$this->cart->total().'</td>
</tr>
</table>
<button type="submit" name="basket" class="btn btn-danger btn-lg basket" ><i class="fa fa-shopping-cart" aria-hidden="true"></i></button>
</div>';
if($count == 0){
$output = '<h3>Cart is Empty</h3>';
}
return $output;
}
public function basket(){
if ($cart = $this->cart->contents()){
foreach ($cart as $item){
$order_detail = array(
'tblItemsID' => $item['id'],
'tblLoginID' => $this -> session -> userdata('user_id'),
'Qty' => $item['qty'],
'price' => $item['price'],
'total' => $item['subtotal']
);
$this->db->insert('tblShoppingCart', $order_detail);
}
}
}
}
Note:In product_controller.php i coded button to copy cart items to another table. on button click event i wrote in jquery ajax below
jquery Ajax:
<script>
$(document).ready(function(){
$('.add_cart').click(function(){
var product_id=$(this).data("productid");
var product_name=$(this).data("productname");
var product_price=$(this).data("price");
var quantity=$('#' + product_id).val();
if(quantity != '' && quantity >0)
{
$.ajax({
url:"<?php echo base_url();?>products/add",
method:"POST",
data:{product_id:product_id,product_name:product_name,product_price:product_price ,quantity :quantity},
success:function(data)
{
alert("Product Added into cart");
$('#cart_details').html(data);
$('#' + product_id).val('');
}
});
}
else
{
alert("Please Enter Quantity");
}
});
$('#cart_details').load("<?php echo base_url();?>products/load");
$(document).on('click','.remove_inventory',function(){
var row_id = $(this).attr("id");
if(confirm("Are you sure you want to delete item")){
$.ajax({
url:"<?php echo base_url();?>users/remove",
method:"POST",
data:{row_id:row_id},
success:function(data)
{
alert("Product remove fromm cart");
$('#cart_details').html(data);
}
});
}else{
return false;
}
});
$(document).on('click','#clear_cart',function(){
if(confirm("Are you sure you want to delete item"))
{
$.ajax({
url:"<?php echo base_url();?>products/clear",
success:function(data)
{
alert("Are you sure you want clear cart?");
$('#cart_details').html(data);
}
});
}
else{
return false;
}
});
$(document).on('click','.basket',function(){
if(confirm("Are you sure you want to delete item"))
{
$.ajax({
url:"<?php echo base_url();?>products/basket",
method:"POST",
success:function(data)
{
alert("Are you sure?");
window.location="users/basket";
}
});
}
else{
return false;
}
});
});
</script>
----------
Use this code on your needed redirect place:
where you will retrieve the response via ajax success response (date);
before that you will return the value in server side which mean controller.
$.ajax({
url:"<?php echo base_url();?>products/basket",
method:"POST",
success:function(data)
{
alert("Are you sure?");
location.href = data.url_path;
}
});
Use window.location.href
$.ajax({
url:"<?php echo base_url();?>products/basket",
method:"POST",
success:function(data)
{
alert("Are you sure?");
window.location.href="<?php echo base_url();?>users/basket";
}
});
after ajax success just write.
window.location.href="redirect_location_name";

AJAX event works but not reflect PHP MYSQL result simultaneously without refresh.

Hello guys I am new to AJAX and I'm developing DB list like CRUD and one of delete feature I used with AJAX actually it deletes record but only reflect after manual refresh not simultaneously so I need your help with AJAX.
List.php
<?php
include "db.php";
$sql = "SELECT * FROM users";
$query = $conn->query($sql);
?>
<script src="https://code.jquery.com/jquery-3.2.1.js" integrity="sha256-DZAnKJ/6XZ9si04Hgrsxu/8s717jcIzLy3oi35EouyE="
crossorigin="anonymous"></script>
<script>
$(document).ready(function() {
$(document).on('click','#btn_delete',function(){
var uid = $(this).data("id1");
if(confirm('Are You Sure To Delete '+uid+' ?'))
{
$.ajax({
url: 'delete.php',
type: 'POST',
data: 'uid='+uid,
dataType: 'text',
success:function(data){
//alert(data);
}
});
}
});
});
</script>
<table border="1">
<tr>
<th>ID</th>
<th>Name</th>
<th>Contact</th>
<th>Skills</th>
<th>Edit</th>
</tr>
<?php
while($row = $query->fetch_object()){
//echo $row->name."<br>";
?>
<tr>
<td><?php echo $row->uid; ?></td>
<td><?php echo $row->name; ?></td>
<td><?php echo $row->contact; ?></td>
<td><?php echo $row->skills; ?></td>
<td id="edit">
<button calss="delete_btn" type="submit" id="btn_delete" name="delete" value="DELETE" data-id1="<?php echo $row->uid; ?>">DELETE</button>
<!-- <a href="delete.php" data-id2="<?php echo $row->uid; ?>" id="delete" alt="DELETE" >Delete</a> -->
Update
</td>
</tr>
<?php } ?>
</table>
Whenever I press Delete button it actually delete record on first hand from database that mean ajax works but simultaneously table is not refresh, deleted entry remain in table till next refresh.
Delete.php
<?php
include "db.php";
$uid = $_POST['uid'];
$sql = "DELETE FROM users WHERE uid='".$uid."'";
$conn->query($sql);
$conn->close();
?>
<p id="check">Deleted</p>
I see some issues with this code and currently only partial or round about answers so I thought I would lend a hand :)
The dynamic rows you create inside your while loop have buttons that have a static ID across all delete buttons.
This could cause problems because ID's are supposed to be unique.
You misspelled class.
I removed the ID, corrected the spelling on class, and updated the JavaScript to use the button class instead of ID.
Since the button is in the table we can use it as a marker for which row to remove from the table.
This can be accomplished by calling closest: var tr = $(this).closest("tr");
Once the AJAX succeeds we can now remove that row: tr.remove();
The jQuery AJAX function has gone through some changes recently as the success callback was deprecated and then removed in 3.0 see Deprecation Notice.
This would cause your success call to not fire as it doesn't exist in 3.0 and from your question we can see that your using version 3.2.1.
I have replaced the callback with the updated call.
Here is the solution I came up with:
<script>
$(document).ready(function() {
$(document).on("click", ".btn_delete", function(){
var tr = $(this).closest("tr");
var uid = $(this).data("id1");
if (confirm("Are You Sure To Delete " + uid + "?")) {
$.ajax({
url: "delete.php",
type: "POST",
data: "uid=" + uid,
dataType: "text",
done: function(data){
tr.remove();
}
});
}
});
});
</script>
<table border="1">
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Contact</th>
<th>Skills</th>
<th>Edit</th>
</tr>
</thead>
<tbody>
<?php
while($row = $query->fetch_object()){
//echo $row->name."<br>";
?>
<tr>
<td><?php echo $row->uid; ?></td>
<td><?php echo $row->name; ?></td>
<td><?php echo $row->contact; ?></td>
<td><?php echo $row->skills; ?></td>
<td id="edit">
<button class="delete_btn" type="submit" name="delete"
value="DELETE" data-id1="<?php echo $row->uid; ?>">DELETE</button>
<a href="form.php?link=<?php echo $row->uid; ?>"
value="<?php echo $row->uid; ?>" alt="UPDATE">Update</a>
</td>
</tr>
</tbody>
<?php } ?>
</table>
On another note the PHP call to your MySql in Delete.php is susceptible to injection attacks here is some documentation on that in PHP < 5.5 see Example 5.50 An example SQL Injection Attack and in PHP >= 5.5 as the function was deprecated in 5.5.
You can delete the element in the success callback function like so:
$.ajax({
url: 'delete.php',
type: 'POST',
data: 'uid='+uid,
dataType: 'text',
success:function(data){
//if using jquery
//$('tr').filter(':has(td:first:contains(' + uid + '))').remove();
$('tr').filter(function() {
return $(this).find('td:first').text() == uid;
}).remove();
//if not
var table = document.getElementsByTagName('table')[0];
var rows = table.getElementsByTagName('tr');
for (var i = 0; i < rows.length; i++) {
if (rows[i].children[0].textContent == uid) {
table.removeChild(rows[i]);
}
}
}
});
You can use this:
$.ajax({
url: 'delete.php',
type: 'POST',
data: 'uid='+uid,
dataType: 'text',
success:function(data){
window.location.href = 'YOUR PAGE';
}
})
You can make the page to reload automatically after successful ajax call. Try This:
$.ajax({
url: 'delete.php',
type: 'POST',
data: 'uid='+uid,
dataType: 'text',
success:function(data){
location.reload();
}
})

Cant click on button with is loaded with ajax

I am loading a content into a #result div. In that content, there is a button.
After the contrnt was loaded with ajax, i cant click on that button, i dont get the alert. (the page doesnt see it? :))
<script type="text/javascript">
$(document).ready(function(e)
{
$('#printButton').hide();
$('#submitButton').click(function(e)
{
var kat = $('#kategoria').val();
$.ajax({
type: 'POST',
url: 'files/get_arlista_kategoria.php',
data: { kat: kat },
dataType: "html",
cache: false,
beforeSend: function(){
$('#preloaderImage2').show();
},
success: function(data)
{
var result = $.trim(data);
$('#result').html(result);
$('#printButton').show();
},
complete: function(){
$('#preloaderImage2').hide();
}
});
});
// This click doesnt work
$('#savePrices').click(function(e)
{
alert("Its oké");
});
});
</script>
How can i work with this button and the input after the ajax loaded it? I want to update the product prices.
And here is the php file, this generates the html content:
<?php
include_once("../../files/connect.php");
include_once("../../files/functions.php");
if(!empty($_POST))
{
$kategoria = mysqli_real_escape_string($kapcs, $_POST['kat']);
$sql = "SELECT termek_id, termek_nev, termek_akcio, termek_normal_ar, termek_akcios_ar, mertekegyseg_nev FROM termek
LEFT JOIN webshop_mertekegyseg ON webshop_mertekegyseg.mertekegyseg_id = termek.termek_egyseg
WHERE
termek_id IN (SELECT kat_kapcs_termek_id FROM `termek_katgoria_kapcsolo` WHERE kat_kapcs_kategoria_id IN ($kategoria) ) ORDER BY termek_nev ASC";
$get = mysqli_query($kapcs, $sql) or die(mysqli_error($kapcs));
$num = mysqli_num_rows($get);
if($num > 0 )
{
echo '<form method="post">';
echo '<table class="form manufacturer-seo-form table table-hover">';
echo '<thead style="font-weight:bold;">
<tr>
<td style="text-align: left;">ID</td>
<td class="left">Megnevezés</td>
<td style="text-align: left;">Egység</td>
<td>Bruttó ár</td>
<td>Akciós ár</td>
<td style="text-align: center;">Akciós</td>
</tr>
</thead>';
echo '<tbody>';
while($i = mysqli_fetch_assoc($get))
{
?>
<tr id="sor<?php echo html($i['termek_id']); ?>">
<td style="text-align: left;"><?php echo html($i['termek_id']); ?></td>
<td class="left"><a title="Megnyitás" style="color:#333;" target="_blank" href="termek-szerkesztes.php?id=<?php echo html($i['termek_id']); ?>"><?php echo html($i['termek_nev']); ?></a></td>
<td style="text-align: left;"><?php echo $i["mertekegyseg_nev"] ?></td>
<td><input type="text" name="normal_ar" value="<?php echo html($i['termek_normal_ar']); ?>" /></td>
<td><input type="text" name="akcios_ar" value="<?php echo html($i['termek_akcios_ar']); ?>" /></td>
<td style="text-align: center;">
<select name="termek_akcio" class="input input-select" style="padding:5px 10px">
<?php
$ertek = intval($i['termek_akcio']);
$values = array("1" => "Igen", "0" => "Nem");
foreach($values AS $k => $v)
{
$selected = $ertek == $k ? ' selected="selected"':'';
echo '<option ' . $selected . ' value="' . $k . '">' . $v . '</option>';
}
?>
</select>
</td>
</tr>
<?php
}
echo '</tbody>';
echo '</table>';
echo '<div class="text-center"><button class="btn saveButton" type="button" id="savePrices">Módosítások mentése</button></div>';
echo '</form>';
}
else
{
echo '<span style="display:block;margin:20px 0 20px 5px;"><b>A kiválasztott kategóriában nincsenek termékek.</b></span>';
}
}
?>
You assign the click event function before the element (button) actually exists. Therefore there is no element to bind the click event to. You can bind the click event to the document instead:
$(document).on('click', '#savePrices', function(e) {
alert(...);
});
Completely untested though ...
The onclick assignment ($('#savePrices').click(...)) is run once when the web page has loaded. But your pricing buttons are not there yet.
Run it again when the AJAX .success is executed:
<script type="text/javascript">
$(document).ready(function(e)
{
$('#printButton').hide();
$('#submitButton').click(function(e)
{
var kat = $('#kategoria').val();
$.ajax({
type: 'POST',
url: 'files/get_arlista_kategoria.php',
data: { kat: kat },
dataType: "html",
cache: false,
beforeSend: function(){
$('#preloaderImage2').show();
},
success: function(data)
{
var result = $.trim(data);
$('#result').html(result);
// assign onclick
$('#savePrices').click(function(e)
{
alert("Its oké");
});
$('#printButton').show();
},
complete: function(){
$('#preloaderImage2').hide();
}
});
});
});
</script>

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

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