How to remove item using shopping cart session Codeigniter - javascript

I am currently developing an ecommerce system and I am already in the part of ordering module. I am using the shopping cart of Codeigniter and it is my first to do it.
Done in a part of add to cart but having problem in remove single item in cart session. When I clicked the Remove, everything in my cart will be remove.
Question: How can I remove a single item in my cart?
View
<?php foreach ($this->cart->contents() as $items): ?>
<tr>
<td><?= $items['name']?></td>
<td><?= $items['qty']?></td>
<td style="text-align:center"><span>₱<?= $this->cart->format_number($items['price'])?></span></td>
<td style="text-align:center"><span>₱<?= $items['subtotal']?></span></td>
<td><button class="btn btn-primary btn-sm"><i class="fa fa-times" aria-hidden="true"><?= $this->cart->remove($items['rowid'])?>REMOVE</i></button></td>
</tr>
<?php endforeach; ?>
Controller
public function remove_cart($rowid)
{
$removed_cart = array(
'rowid' => $rowid,
'qty' => 0
);
$this->cart->update($removed_cart);
}
}

An easy way to remove a row by clicking a button is using JQuery
This is my solution :
HTML , PHP :
<table>
<tr>
<td><!--your PHP code--></td>
<td><!--your PHP code--></td>
<td><span>₱<!--your PHP code--></span></td>
<td><button class="remove">REMOVE</button></td>
</tr>
<tr>
<td><!--your PHP code--></td>
<td><!--your PHP code--></td>
<td><span>₱<!--your PHP code--></span></td>
<td><button class="remove">REMOVE</button></td>
</tr>
</table>
JQuery:
$(document).ready(function(){
$('.remove').click(function(){
$(this).closest('tr').remove();
})
});
that is the link to the example :
http://tpcg.io/J0Uv2H

This code removes the cart items
<td><button class="btn btn-primary btn-sm"><i class="fa fa-times" aria-hidden="true"><?= $this->cart->remove($items['rowid'])?>REMOVE</i></button></td>
this part
<?= $this->cart->remove($items['rowid'])?>
Here it gets removed
remove the code and you can try like this.
<td>
<a href="<?= base_url().'user/remove_cart/'.$items['rowid']; ?>">
<button class="btn btn-primary btn-sm"><i class="fa fa-times" aria-hidden="true">REMOVE</i></button>
</a>

You should not use Shopping cart class from Codeigniter. It has been deprecated.
You should implement your own. We are using Codeigniter for our custom ecommerce app, and i can tell you that using makes much more sense. I have never seen any point in using Codeigniter shoping cart class.
It is nothing more than wrapper around Session.

Try like this one:
function remove($id) {
if ($id === "all"){
$this->cart->destroy();
}
else{
// Destroy selected rowid in session.
$data = array(
'rowid' => $this->input->post('id'),
'qty' => 0
);
$this->cart->update($data);
}
$this->load->view('users/cart_function');
}
check $rowid has a value.

Related

show/hide icons in div in table row using jquery

I have a table, its is data displayed using foreach. one column have 3 icons, by default they are hidden. And also have checkbox. icons and checkbox are in every row. Now when select any checkbox, icons of all rows are appearing. Instead I want only one row icons should be displayed on selecting checkbox. Can somebody help please. thanks in advance. here is the code.
in view
<?php $sn= $this->uri->segment(4); foreach($companies as $company){ $sn++;?>
<tr class="parent" style="font-size:11px;color:#3D4061;border-bottom:1px solid #3d406136">
<td><input type="checkbox" class="text-center check_data mt-2" onchange="changevalue()"></td>
<td class="text-center" style=""><h6><?php echo $sn; ?></h6></td>
<td class="text-center" style=""><h6><?php echo $company->company_name; ?></h6></td>
<td class="text-center" style=""><h6><?php echo $company->contact_no; ?></h6></td>
<?php if($company->activation_status == 1){?>
<td class="text-center" style=""><h6 class="text-success font-weight-bold" style="font-size:13px">Active</h6></td>
<?php } ?>
<?php if($company->activation_status == 0){?>
<td class="text-center" style=""><h6 class="text-danger font-weight-bold" style="font-size:13px">Inactive</h6></td>
<?php } ?>
<td class="text-center" style="">
<div class="status">
<i class="fa fa-edit"></i>
<?php if($company->activation_status == 0){?>
<i class="fa fa-dot-circle-o"></i>
<?php }else{ ?>
<i class="fa fa-exclamation-triangle"></i>
<?php } ?>
<i class="fa fa-trash-alt"></i>
</div>
</td>
<td ><i class="fa fa-chevron-down down" ></i></td>
</tr>
and script is
<script>
$('.status').hide();
function changevalue(){
if($(".check_data").is(":checked"))
$('.status').show();
else
$(".status").hide();
$('.cchild').hide();
}
</script>
you can also use .parent() and .find() methods to get specific row like that:
<input type="checkbox" function="changevalue(this)">
and your javacript must be like that:
function changevalue(elem){
if($(elem).is(":checked"))
$(elem).parent().parent().find('.status').show();
else
$(elem).parent().parent().find('.status').hide();
}
This code can be simplified but it's a good starting example to understand parent-child usage of html elements. At this example first .parent() goes to <td> of checkbox element and second .parent() goes to <tr> element then it searches for .status class in it then hides it.
and you can simplfy it like that:
function changevalue(elem){
if($(elem).is(":checked"))
$(elem).parents("tr").find('.status').show();
else
$(elem).parents("tr").find('.status').hide();
}
function changevalue() {
var $this = $(this),
$status = $this.parents("tr").find(".status");
if ($this.is(":checked")) {
$status.show();
} else {
$status.hide();
}
}
You can give dynamic Ids to every checkbox and status div. Use your record's id may be companyId to create Ids like
<input type="checkbox" id="checkbox_('<?php echo $company->id; ?>')>
I don't know the syntax for php.
and then you can pass the current companyId in onchange="changevalue(companyId)"
and then your code will be like this
function changevalue(companyId){
if($("#checkbox" + companyId).is(":checked"))
$('#status' + companyId).show();
else
$("#status" + companyId).hide();
}

Retrieve a specific row value from table HTML and submit it to PHP

I'm populating a table from my database and it looks like this :
<form name = "Form" role="form" action ="php/teilnehmen.php" method="POST">
<fieldset>
<table width="100%" class="table table-striped table-bordered table-hover" id="dataTables-example">
<thead>
<tr>
<th>ID</th>
<th>Studienfach</th>
<th>Teilnehmer/in</th>
<th>Teilnehmen</th>
</tr>
</thead>
<tbody>
//<?php php code.....
$i =0;
$sizeofstudienfaecherseperate =
count($studienfaecherseperate);
for ($i; $i < $sizeofstudienfaecherseperate; $i++) {
?>
<tr class="odd gradeX">
<td ><?php echo($i+1);?></td>
<td class="studienfach"><?php echo($studienfaecherseperate[$i]);?>
<input type="hidden" name="PARAM_STUDIENFACH" id="PARAM_STUDIENFACH"
value="<?php echo($studienfaecherseperate[$i]);?>"> </input>
</td>
<td ><?php echo($teilnehmer[$i]);?></td>
<td width="10%">
<?php if ($teilnahmestatus[$i] =="0"){ ?>
<button type="submit" class="btn btn-success use-address"
name="teilnehmern"id="teilnehmen">Teilnehmen</button>
<?php }else{?>
<button type="submit" class="btn btn-danger use-address" name="teilnahme-beenden"
id="teilnahme-beenden">Teilnahme beenden</button>
<?php }?>
</td>
</tr>
<?php } ?>
</tbody>
</table>
</fieldset> <!-- /.table-responsive -->
the table is shown great, and my problem is when i try to submit my second column value "PARAM_STUDIENFACH" of a specific row to my php webservice. It always gives me back the last value. I know that because I'm using the same id in every row so it will be overwritten. I tried using JavaScript to return the value of the clicked row from other questions in the forum but it didn't work for me. I'm using a bootstrap table if that helps.
EDIT 1 :
Thanks to #Taplar answer I managed to find a solution to my problem. I used this JavaScript to retrieve the data and ajax to send a post request. This is the code I used :
$(".use-address").click(function() {
var item = $(this).closest("tr") // Finds the closest row <tr>
.find(".studienfach") // Gets a descendent with class="nr"
.text(); // Retrieves the text within <td>
$.ajax({
type: "POST",
dataType: "json",
url: "php/teilnehmen.php",
data: {PARAM_STUDIENFACH:item},
success: function(data){
alert(item);
},
error: function(e){
console.log(e.message);
}
});
});
my problem now is in the alert the "item" shows correctly but in my database it is saved as the following example :
item = a (shows in alert a)
item = a \n (it's saved like that in the database with spaces afeter \n)
i tried to trim the item before sending it but i got the same result
to get the item sent by ajax i'm using this line of code in :
$studienfach = null;
if(isset($_POST['PARAM_STUDIENFACH']))
$studienfach = $mysqli->real_escape_string($_POST['PARAM_STUDIENFACH']);
EDIT 2:
i managed to solve my second problem by doing this :
$pos= strpos($studienfach, "\\");
$studienfachtemp = substr($studienfach, 0,$pos);
trim($studienfachtemp);
if there is more elegent or correct way to do it ! please post it ! thank you all.
<elem1>
<elem2 class="getMe"></elem2>
<elem3></elem3>
</elem1>
Quick contextual lookup reference. Say you have a click event bound on all 'elem3' on your page. When you click it you want to get the associated 'elem2', not all of them. With the class you can contextually look this element up by doing...
//'this' being the elem3 that was clicked
$(this).closest('elem1').find('.getMe');
From the element you clicked, it will find the shared 'elem1' parent of both 'elem2' and 'elem3' and then find only the '.getMe' that belongs to that parent.
More reading material: http://learn.jquery.com/using-jquery-core/working-with-selections/

Getting user from db and appending to element

This might be a simple question but have kept me busy for the best part of a hour.
I have the following script which generates all active reservations, in the table reservations
require("../includes/connect.php");
function dispAllReservations(){
$i= 1;
global $db;
$date = date('Y-m-d');
$sql ="SELECT * FROM
reservations WHERE pickup_date > '$date'";
$statement = $db->prepare($sql);
$statement->execute();
$bookings = $statement->fetchAll();
$statement->closeCursor();
echo'<table cellpadding="0" cellspacing="0" class=
"table-responsive gzblog-table" id="gzhotel-booking-booking-id">
<thead>
<tr>
<th class="date-th">Reservation ID</th>
<th class="title-th">Car Group</th>
<th>Pickup Date</th>
<th>Return Date</th>
<th>Customer</th>
<th>Email</th>
<th>Amount</th>
<th></th>
<th></th>
<th></th>
</tr>
</thead>
<tbody>';
foreach($bookings as $booking){
if($i%2 == 0){
$class = 'odd';
}
else{
$class = 'even';
}
echo' <tr class='.$class.'>';
echo'<td>'.$booking['res_id'].'</td>';
echo'<td>'.$booking['car_group'].'</td>';
echo'<td>'.$booking['pickup_date'].'</td>';
echo'<td>'.$booking['return_date'].'</td>';
echo'<td>'.$booking['renter_name'].'</td>';
echo'<td>'.$booking['email'].'</td>';
echo'<td>AMOUNT HERE</td>';
echo'<td><a class="btn btn-primary btn-sm fancybox" href="#email">
<span class="glyphicon glyphicon-envelope"></span></a>
</td>';
echo'<td><a class="btn btn-success btn-sm">
<span class="glyphicon glyphicon-pencil"></span></a>
</td>';
echo'<td><a class="btn btn-danger btn-sm icon-delete">
<span class="glyphicon glyphicon-trash"></span></a>
</td>';
echo'</tr>';
}//foreach
echo'</tbody>';
echo'</table>';
}//function
The output of the script generates the following
My Problem / Question
When delete button is clicked -- I need to ensure the correct reservation is deleted, same with the edit button, if edit button is clicked I need to ensure the correct user is edited.
What I need to do
I'm guessing I would need to find a way to append the corresponding value for each user in the loop to the element.
I was thinking of a textbox setting display none and then echoing the value inside the value attribute, but that didn't work...
I'm really stuck here any advise would be appreciated
NOTE: All emails are fictional
Try this:
<a class="btn btn-primary btn-sm fancybox" href="#email" onclick="onDelete(your-id)">
<span class="glyphicon glyphicon-trash"></span>
</a>
<a class="btn btn-primary btn-sm fancybox" href="#email" onclick="onEdit(your-id)">
<span class="glyphicon glyphicon-pencil"></span>
</a>
Create this function:
<script>
//Delete function
function onDelete(id){
$.ajax({
// do someting
});
}
// Edit function
function onEdit(id){
$.ajax({
// do someting
});
}
</script>
You did not tell us at all how do you want to edit/delete you reservations, but based on the tags you used you can take this approach...
1) In your PHP script generate data attributes on rows or cells, like this:
<tr data-id="put_reservation_id_here">
2) And then use jQuery to hook actions to various elements in the table:
$('#gzhotel-booking-booking-id').on('click', '.icon-delete', function() {
var reservationId = $(this).closest('tr').data('id');
// now you have reservation ID and do whichever AJAX call with it
});
You can use data attributes in your html and then get the data attribute value using javascript.
Example:
In your button:
<a class="btn btn-danger btn-sm icon-delete" data-id="your_Id"><span class="glyphicon glyphicon-trash"></span></a>
Replace your_Id with the correct id.
Then using javascript on your onClick event:
$(this).data('id');
This will retrieve the id that you need to handle the action.
Hope this helps.

sending jQuery sortable data via ajax

I am working with jQuery Sortable and twitter bootstrap as well. I have table rows that I am trying to sort. The drag and drop is working fine but I am trying to send the new sort order via ajax which is not picking up/sending the sort order and when i try to alert the data it seems empty.
This is my PHP code which is using loop to pull the records from MySQL
<table class="table table-striped table-bordered ">
<thead>
<tr>
<th> Slide Title</th>
<th> Action</th>
</tr>
</thead>
<tbody>
<?php
while ($row = $query->fetch(PDO::FETCH_ASSOC)) {
?>
<tr id="<?php echo $row['id']; ?>">
<td>
<?php echo $row['title']; ?>
</td>
<td>
<div class="btn-group pull-right">
<button data-toggle="dropdown" class="btn btn-small btn-info dropdown-toggle">
Action<span
class="caret"></span></button>
<ul class="dropdown-menu">
<li>Edit
</li>
<li>
Delete
</li>
</ul>
</div>
</td>
</tr>
<?php
}
?>
</tbody>
</table>
and this is the java script that is doing the sorting and then sending data to a file called slides.php
$(document).ready(function(){
$(function() {
$('table').sortable({
items: 'tr',
opacity: 0.6,
axis: 'y',
stop: function (event, ui) {
var data = $(this).sortable('serialize');
alert(data);
$.ajax({
data: data,
type: 'POST',
url: 'slides.php'
});
}
});
});
});
What I feel is my variable data var data = $(this).sortable('serialize'); is not working, if i send a static variable then I am able to see that in $_POST
I will really really appreciate any assistance in this.
I ended up following up the concept mentioned on this link to do my task, for some reason current solution was not working with <table> so I just re wrote the html part using <ul></ul> and it worked.
I hope this helps anyone out there having the same problem.

deleting entire row with jquery json ajax php

What I want to achieve is to delete an entire row. First I display the table, then if you click on "delete" button from every row then a confirmation modal shows up asking you if you want to delete that row.
I'm trying to work with jquery, ajax, json and PHP. I'm still learning of course.
So far what I have is this:
Javascript file:
function callToModal(data){
$('#myModal3 .modal-body p').html("Desea eliminar al usuario " + '<b>' + data + '</b>' + ' ?');
$('#myModal3').modal('show');
$('.confirm-delete').on('click', function(e) {
e.preventDefault();
var id = $(this).data('id');
$('#myModal3').data('id', id).modal('show');
});
$('#btnYes').click(function() {
// handle deletion here
var id = $('#myModal3').data('id');
alert(id);
$.ajax({
url: "deleteFrontUser",
type: 'POST',
data: {
id:id
},
success: function(html){
//alert(html);
$('[data-id='+id+']').parents('tr').remove();
$('#myModal3').modal('hide');
}
});
return false;
});
};
In my admin.php file:
public function deleteFrontUser(){
// var_dump($_POST['id']);die();
$rowId = $_POST['rowId'];
$result = array();
$front = UserDs::getInstance()->getUserById($id);
UserDs::getInstance()->deleteItem($front);
$result["message"] = "Usuario eliminado";
echo json_encode($result);
}
The view (please notice that I'm using Smarty template engine):
<div class="portlet-body">
<table class="table table-striped table-hover table-users">
<thead>
<tr>
<th>Avatar</th>
<th class="hidden-phone">Usuario</th>
<th>Nombre</th>
<th>Apellido</th>
<th class="hidden-phone">Email</th>
<th class="hidden-phone">Provincia</th>
<th class="hidden-phone">Miembro desde</th>
<th>Estado</th>
<th></th>
<th></th>
</tr>
</thead>
<tbody>
{foreach $frontusers as $frontuser}
<tr>
{if $frontuser->frontavatar_id eq null}
<td><img src="{site_url()}assets/img/avatar.png" alt="" /></td>
{else}
<td><img src="{site_url()}assets/img/avatar1.jpg" alt="" /></td>
{/if}
<td class="hidden-phone">{$frontuser->username}</td>
<td>{$frontuser->name}</td>
<td>{$frontuser->lastname}</td>
<td class="hidden-phone">{$frontuser->email}</td>
<td class="hidden-phone">{$frontuser->state}</td>
<td class="hidden-phone">{$frontuser->creation_date|date_format:"%Y/%m/%d"}</td>
{if $frontuser->status eq 2}
<td ><span class="label label-success">Activo</span></td>
{else}
<td ><span class="label label-warning">No Activo</span></td>
{/if}
<td><a class="btn mini blue-stripe" href="{site_url()}admin/editFront/{$frontuser->id}">Modificar</a></td>
<td>Eliminar</td>
</tr>
<!-- modal -->
<div id="myModal3" class="modal hide fade" tabindex="-1" role="dialog" aria-labelledby="myModalLabel3" aria-hidden="true">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true"></button>
<h3 id="myModalLabel3">Eliminar</h3>
</div>
<div class="modal-body">
<p></p>
</div>
<div class="modal-footer">
<button class="btn" data-dismiss="modal" aria-hidden="true">Cerrar</button>
<button data-dismiss="modal" class="btn red" id="btnYes">Confirmar</button>
</div>
</div>
<!-- end modal -->
{foreachelse}
<tr>
<td colspan="2"><span class="text-error"><i class="icon-exclamation"></i> No hay Usuarios cargados.</span></td>
</tr>
{/foreach}
</tbody>
</table>
</div>
The modal displays when you click on delete button of an specific row, but here's the funny thing: the first time you press delete, it doesn't erase the row. When you press that or any other row (after pressing once delete) the row is deleted. So that is one problem, and the other problem is that I can't manage to send data to my php file so I can erase it from the database.
How can i solve this?
I have a customized fiddle with this, if you want to check out: code
url has to be a valid site located within your website, you can't have a function name within url, since the AJAX call won't know in which file the function is located.
So your url must be:
url: "admin.php"
You can, however, add another parameter into your AJAXcall to tell admin.php which function it should execute, something like this would work:
$.ajax({
url: "admin.php",
type: 'POST',
data: {
id:id,
func:"deleteFrontUser"
},
success: function(html)
{
//alert(html);
$('[data-id='+id+']').parents('tr').remove();
$('#myModal3').modal('hide');
}
});
So on admin.php you must receive the posted data BEFORE you enter the function, and you can parse the func variable to tell which function to execute:
$rowId = $_POST['id'];
$func = $_POST['func'];
switch ($func)
{
case 'deleteFrontUser':
deleteFrontUser($rowId);
break;
default:
// function not found.
break;
}
Wherea deleteFrontUser looks something like this:
public function deleteFrontUser($rowId)
{
$result = array();
// Rest of the code.
echo json_encode($result);
}
Maybe you need to modify this a bit but this should give you the idea.
For more information take a look at the $.ajax documentation.
Note:
For best practice's cause, use php's isset function to determine whether the data was actually posted or not. The ternary operator makes this very easy and short:
$emptyString = "";
$rowId = isset($_POST['id']) ? $_POST['id'] : $emptyString;
$func = isset($_POST['func']) ? $_POST['func'] : $emptyString;
I also recommend using jQuery's .on function, and let it take the parameter "click" and the function of which will be triggered on the click event. .click is in general bad practice because it's unable to detect changes within the DOM tree so when you update it with new HTML you're screwed, .on allows you to add new elements to the dom tree but still being able to listen to events corresponding to them.
Solution is this:
See my previous post in order to have the correct js file and view: post
Php code for deleting entire row from the database would be:
public function deleteFrontUser(){
$rowId = $_POST['id'];
$result = array();
$front = UserDs::getInstance()->getUserById($rowId);
UserDs::getInstance()->deleteItem($front);
$result["message"] = "Usuario eliminado";
echo json_encode($result);
}

Categories

Resources