I make the cart with a separate page. When view cart button is clicked I load the php file of the cart. Where I loop the cart session variable array and show in the page. But, when the user press delete button of an item it should be deleted and not shown after in the cart page. Now, how can I automatically update the cart page without reloading the page?
I need some idea how can I implement this?
loop part
<?php foreach($_SESSION['cart'] as $result)
{
?>
delete button
<div class="col-sm-6">
<div class="row">
<div class="col-sm-2">
<h6><strong><?php echo $result['price']; ?><span class="text-muted"> x</span></strong></h6>
</div>
<div class="col-sm-4">
<input type="text" class="form-control input-sm" value=<?php echo $result['quantity']; ?>>
</div>
<div class="col-sm-2">
<button type="button" class="btn btn-link btn-sm">
<span class="fa fa-trash"> </span>
</button>
</div>
</div>
</div>
full source code here
Edit 1
suppose I get the page by ajax call
$.ajax(
{
url: 'makeCartPage.php',
type: 'POST',
success: function(msg)
{
//here to code to show the new cart page/information
},
error: function()
{
console.log('cart error');
}
});
But, there was a challenge to show the ajax return data.
There are a couple ways to do this, but one way is to not refresh the list, but rather hide the item you delete, so add a class to the top-level row wrapper class like product-wrapper or what-have-you:
<div class="row product-wrapper">
When you click the x button, you run the ajax, update the session on the makeCartPage.php page, and on success you traverse the DOM using $(this) and hide the product-wrapper class. Something like:
$('.text-muted').on('click',function(){
// Isolate the clicked button
var deleteButton = $(this);
// Run ajax to remove the item out of the session
$.ajax({
url: 'makeCartPage.php',
type: 'POST',
data: {
"id": /* get your product id here however you are able so you can remove from the session */
},
success: function(response) {
// You want to send back a delete success response when you actually
// remove it from the session. If true, do something similar to this
deleteButton.parents('.product-wrapper').fadeOut('fast');
},
error: function(){
console.log('cart error');
}
});
});
This should be enough info to get you started. Here is a fiddle of the hiding fx:
https://jsfiddle.net/efL891mu/
Related
I am trying to use AJAX to dynamically delete a record from the database through the front end site, I have the code but when I click the delete button nothing happens, there is connection to the database I just cannot find the mistake in the code, all the code files are linked to one another.
The table I want to delete a record from is called recipes.
HTML
<div id="recipecards2" class="row">
<div class="col-sm-3">
<div id="recipecards" class="card">
<div class="card-body">
<p>
<button type="button" id="deletebutton" class="btn btn-outline-danger" input type="submit" name="recipe_delete" data-id="<?php echo $recipe['recipe_id']; ?>">
<i style=color:black; class="fa fa-trash-o"></i> Delete Recipe </button> </a>
</p>
</div>
</div>
<br>
</div>
Ajax PHP code
<?php
require_once('../includes/db.php');
if($_POST['itemid']){
$query = "DELETE FROM recipes WHERE itemid= $recipe_data['recipe_id'];";
$result = $DBH->prepare($query);
$result->bindParam(':itemid', $_POST['itemid']);
$result->execute();
echo $_POST['itemid'];
}
?>
Javascript
$('#recipecards2').on('click', '#deletebutton', function() {
// var that = this;
var itemid = $('#recipecards').attr('data-id');
var request = $.ajax({
url: "ajax/removeItemsFromList.php",
type: "post",
data: { itemid : itemid}
});
// If we're successfull!
request.done(function (response, textStatus, jqXHR){
$('#recipecards2 > #recipecards[data-id="'+response+'"] ').remove();
});
});
Firstly, your issue is that you are using named parameters incorrectly, you are prepareing your query, yet at the same time you are passing a value directly to it.
Change,
$query = "DELETE FROM recipes WHERE itemid= $recipe_data['recipe_id'];";
To,
$query = "DELETE FROM recipes WHERE itemid = :itemid;";
Secondly, if you are using the data-* properties, consider using the respective .data() function too.
Thirdly, when you do an AJAX request and it doesn't go right, open your browser console and check the response of that request. That generally should point you in to the right direction.
Fourthly, your HTML for your button is malformed, take a look at your button code,
<button type="button" id="deletebutton" class="btn btn-outline-danger" input type="submit" name="recipe_delete" data-id="<?php echo $recipe['recipe_id']; ?>">
Notice how you have a button/input mix? Pick one, you don't need to have both.
I'm working on add to compare feature of a website,so on current page there are some results which have a checkbox named add to compare attached.
So when user click on add to compare checkbox the selected result get appended to one compare box div and this process go on.
my problem is,when user want to uncheck or remove the selected result from compare div box he should be able to remove it.
Here's is my code which i have done till yet
html
<div id='compare_box'>
<form action="compare_results.php" method="POST">
<div id='result'>
</div>
<button id="compare_submit" type="submit" class="btn btn-primary btn-sm">compare</button>
</form>
</div>
<div class="col-md-3 photo-grid " style="float:left">
<div class="well well-sm">
<h4><small><?php echo $title; ?></small></h4>
<br>
<div class="features">
<div id="compare_feature">
<input type ='checkbox' name="compare" class="compare" value="<?php echo $id;?>">add to compare
</div>
<button class='btn btn-sm btn-info favourite_feature' value="<?php echo $id;?>">add to favourite</button>
</div>
</div>
</div>
css
#compare_box
{
display: none;
}
ajax call
$(".compare").change(function() {
if(this.checked) {
$('#compare_box').show();
var check = $(this).val();
$.ajax({
type: 'POST',
url: 'compare.php',
dataType : "JSON",
data:{value : check},
success: function(data)
{
console.log(data);
console.log(data.id);
var output = "<div class='col-md-3 photo-grid' style='float:left'>";
output += "<div id='course_title' class='well well-sm'>";
output += "<h4>"+data.title+"</h4>";
output+="<textarea class='hidden' id='hidden_title' name='course_title[]' value=>"+data.title+"</textarea>";
output+="</div>";
output+="<input type='hidden' id='hidden_id' name='course_id[]' value="+data.id+">";
output+="</div>";
$('#result').append(output);
}
});
}
});
PS: I'm trying to implement something like this
What is '#compare_box' ? Is it the element that appears when the checkbox disappear (in your exemple at 'your selection')?
Then bind an action on '#result' - precise something that can link your element to check box like an id (when you prepare your html in ajax response).
$('#result').on('click', function() {
$($(this).data('id')).prop('checked', false); // uncheck it
$(this).remove();
});
Do the same for when you uncheck a checkbox (find the element with data-id of your check box and remove it)
EDIT : it's not the perfect code to make it work, you might adapt depending on where you bind click or place the data-id
I'm pulling my hair out over this one - I have a page that searches a MySQL database and returns the results in a table. I want the user to be able to update the results and hence update the MySQL database. The first part works ok, I have a search box on the page, which uses jQuery/ajax to query the database and display the results, e.g.:
<form class="well" id="jquery-submit-ajax" method="post">
<input type="text" name="userSearch" placeholder="Search…">
<label>Name/Email/id</label>
<Br />
<input type="submit" id="searchButton" value="Search">
</form>
<div class="alert alert-success hide">
<div id="success-output" class="prettyprint"></div>
</div>
<div id="loading-image" class="alert hide" style="text-align:center">
<img src="../images/ajax-loader.gif" /></div>
<div class="alert alert-error hide">
<div id="error-output" class="prettyprint"></div>
</div>
</div>
and the jQuery:
$("#jquery-submit-ajax").submit(function(e) {
$('#loading-image').fadeIn();
$.ajax({
type: "POST",
url: "jquery-ajax-control.php",
data: $(e.target).serialize(),
dataType: "html",
beforeSend:function(){
$('.alert-error,.alert-success').hide();
},
error: function(jqXHR, textStatus, errorThrown){
$('#loading-image').hide();
$('.alert-error').fadeIn();
$('#error-output').html(errorThrown);
},
success: function(data){
$('#loading-image').hide();
$('.alert-success').fadeIn();
$('#success-output').html(data);
}
});
return false;
});
So the results are parsed into a table for each result. Within that table is a form with a submit button. e.g.:
<form method="post">
<table>
<tr>
<td><input type="text" class="editbox" name="subs-expiry" value="<?php echo $expiry_date; ?>"</td>
</tr>
</table>
<input type="submit" class="updateSubsButtons" value="Update" />
</form>
I'm trying to submit this form via jQuery/Ajax again, but I can't get it to work. Pressing the Update button results in the whole page refreshing. I've stripped the jQuery for this button right back to just display an alert when the button is pressed, but even that doesn't work.
$(".updateSubsButtons").on("submit", function(e){
alert("clicked");
e.preventDefault();
});
Using the Chrome debugger a breakpoint in the function never gets hit, so maybe jQuery can't find the button? I've tried .on() and .live() functions, but I get the same result with both. I really can't figure out what's going on here, so any help would be gratefully received!
Try replacing it with a button, and a 'click' event.
<button class="updateSubsButtons">Update</button>
$(".updateSubsButtons").on("click", function(e){
alert("clicked");
console.log(e);
e.preventDefault();
});
Here's how to deal with asynchronously loaded items(added because this is how the problem was actually fixed.):
$(".AlreadyLoadedParent").on("click",'.buttonYouWantToClick', function(e){
alert("clicked");
console.log(e);
e.preventDefault();
});
First, you "click" a button, you don't "submit" it. You submit the form. So you should work with the event "click".
Second, if the button that should trigger the jQuery code is loaded using AJAX you should bind the event using .live() function like this:
$('.updateSubsButtons').live('click', function(e) {
e.preventDefault();
// Your code here...
}
This way the click event is bound to every new object with class="updateSubsButtons" that is loaded even after the page is loaded. If you use $('.identifier').click() it only works on objects that are already loaded when the page loads and doesn't work on elements being loaded through AJAX.
I have a php page where I add and delete items from database using Jquery + PHP + AJAX.
Now I am able to delete and add when that page loads for the first time.
Now if I first add an element; which in turn adds record to the DB and then updates the div that contains all the listing of divs.
Example:
<div id="all_items">
<div id= "item_1">
<a id="delete_link">...</a>
</div>
<div id= "item_2">
<a id="delete_link">...</a>
</div>
.... Upto Item n
</div>
Now I replace the div with id all_items.
Now I have jQuery at the bottom of the page which calls ajax on a tag of delete_link.
Situtation is:
When page is loaded I can delete any item from the list.
But if I page load i add new item first. (which will update all_items div) after that if I try to click on delete link. Jquery on click selector event is not fired and which in turn doesn't do delete ajax operation.
I couldn't figure out why this is happening.
Looking for some help here.
EDITED:
Sorry for not writing code earliar.
Following is the jQuery I am talking about.
<script type="text/javascript" >
var jQ = jQuery.noConflict();
jQ(function() {
jQ("#submit_store").click(function() {
var store_name = jQ("#store_name").val();
var dataString = 'store_name='+ store_name;
dataString += '&mode=insert';
if(store_name =='')
{
alert("Please Enter store Name");
}
else {
jQ.ajax({
type: "POST",
url: "<?php echo $mycom_url; ?>/store_insert.php",
data: dataString,
cache: false,
success: function(html){
jQ("#dvstoreslists").html(html);
document.getElementById('store_name').value='';
document.getElementById('store_name').focus();
}
});
}
return false;
});
jQ(".store_delete").click(function() {
var store_id = jQ(this).attr('id');
var id = store_id.split("_");
var dataString = 'store_id='+ id[2];
dataString += '&mode=delete';
var to_delete = "#store_list_" + id[2]
jQ.ajax({
type: "POST",
url: "<?php echo $mycom_url; ?>/store_insert.php",
data: dataString,
cache: false,
success: function(html){
jQ(to_delete).hide("slow");
}
});
return false;
});
});
</script>
So If on page load, I delete then delete on click jquery event is fired. But after adding new store and replacing div of stores with new div. then jQuery on click event is not fired.
My HTML is as below.
<div class="sbBox stores">
<form id="add_storefrm" name="add_storefrm" method="post" action="" >
<div class="dvAddStore">
<div class="dvName" id="store_list">
<input type="text" id="store_name" name="store_name">
<input type="hidden" value="addstore" id="mode" name="mode">
</div>
<div class="btnAddStore">
<input type="submit" name="submit_store" value="Add Store" id="submit_store">
</div>
</div>
<div id="dvstoreslists">
<?php
$query = "SELECT * FROM #__shoppingstore order by store_id desc;";
$db->setQuery($query);
$rows = $db->loadObjectList();
foreach($rows as $row)
{
echo "<div class=dvlist id=store_list_".$row->store_id ."><div class=dvStoreListLeft>";
echo "<div class='slname'><h3>" . $row->store_name . "</h3></div>";
?>
<div class="slDelBtn">
<p id = "p_store_<?php echo $row->store_id ; ?>">
<a id="store_delete_<?php echo $row->store_id ; ?>" class="store_delete" alt="Delete" onclick="DeleteStore(<?php echo $row->store_id ; ?>);" >
</a>
</p>
</div>
</div>
</div>
<?php } ?>
</div>
</form>
</div>
Sorry folks for not posting the code earliar.
the ID should always be unique so use class instead
in your case : <a id="delete_link">...</a> to <a class="delete_link">...</a>
When you replace the contents of #all_items any event handlers that were bound to any descendants will no longer exist. You can use event delegation, using the on method, to solve this:
$("#all_items").on("click", ".delete_link", function() {
//Do stuff
});
Notice that I'm using a class selector (.delete_link) instead of an ID selector for the links. It's invalid to have duplicate IDs in the same document.
Also note that the above will only work if you are using jQuery 1.7 or above. For older versions, use delegate instead:
$("#all_items").on(".delete_link", "click", function() {
//Do stuff
});
This works because DOM events bubble up the tree from their target. So a click on a link which is a descendant of #all_items will bubble up through all of its ancestors and can be captured when it reached #all_items.
use live() instead of .bind()
It seems you are trying to delete dynamically added delete_link so i think you should use
$('id or class').on(click,function(){});
i have this bit of html.
(Link at bottom)
Its output of php code for status updates, it has view comments and post comment link, the post comment link uses jquery to add a textarea and submit button below that status update. and the view comments shows the comments to that status update below that status update.
So i use php looping so there will be obviously more than 1 status updates at most times(depends on how much friends users have) so i cant have an element like 'textelement', i will need to have elements like 'textelement1' and 'textelement2'
So i used php to add the id of the status update in the end of the links like _id so the element id becomes view_comments_1.
So i want to use jquery to find out which element has been clicked so that i can add a text box and show comments below the right status update instead of showing it below all status updates.
HTML
<div class="wrapbg">
<span class="corners-top"><span></span></span>
<div id="content"><br/>
Whats new?
<hr class='hr1'>
<div class='stbody' id='stbody'>
<div class='stimg'>
<img src='uploads/profile_pics_small/Anonymous_Blueprint_Wallpaper_by_co.jpg' /></img>
</div>
<div class='sttext'>
Welcome yoall!!
<div class='sttime'>By LUcase</div>
<br><br>
<a href=''>0 Likes</a> <a href=''>1 Dislikes</a>
</div>
<a href=''>unDislike</a> <a id='comment_now_1' href=''>Comment</a> <a id='view_comments1' data-id-1 = '1' href=''>View comments</a> <div id='emptydiv1'> </div></div>
<div class='stbody' id='stbody'>
<div class='stimg'>
<img src='uploads/profile_pics_small/wood_texture_by_pabloalvin-d1igijr.jpg' /></img>
</div>
<div class='sttext'>
hi
<div class='sttime'>By nicknick</div>
<br><br>
<a href=''>0 Likes</a> <a href=''>0 Dislikes</a>
</div>
<a href=''>Like</a> <a href=''>DisLike</a> <a id='comment_now_4' href=''>Comment</a> <a id='view_comments4' data-id-4 = '4' href=''>View comments</a> <div id='emptydiv4'> </div></div></div>
<span class="corners-bottom"><span></span></span>
</div>
JavaScript
//Gotta find out which status update we are dealing with!
jQuery("document").ready(function(){
jQuery(".likebtn").click(function(e) {
var id=jQuery(this).attr("data-id");
jQuery.post('like.php', {'id': id}, function(data) {
alert("Your like.php has been called");
}, "json");
e.preventDefault();
});
jQuery(".dislikebtn").click(function(e) {
});
//gotta figure out which status update we are dealing with!
//attache the click event to the anchor tag
$("#comment_now").live("click",function(e){
//prevent the default behaviour of following the link
e.preventDefault();
$("#comment_now").remove();
//find the textarea element, and after it, put an input tag
$(".sttext").after('<textarea id="comment_text" name="comment"></textarea> <br> <button id = "post_button" class="action greenbtn"><span class="label">Comment</span></button> <a id="cancel_comment" href="">Cancel</a> <br id="com_spacing">');
});
//gotta figure out which status update we are dealing with!
$("#cancel_comment").live("click",function(event){
event.preventDefault();
$("#comment_text").remove();
$("#cancel_comment").remove();
$("#post_button").remove();
$("#com_spacing").remove();
$("#view_comments").before('Comment ');
});
$("#view_comments").live("click", function(e){
e.preventDefault();
var id=jQuery(this).attr("data-id");
$.ajax({
url: 'query_comments.php?status_id='+id,
beforeSend: function( xhr ) {
xhr.overrideMimeType( 'text/plain; charset=UTF-8' );
},
success: function( data ) {
$('#emptydiv').html(data);
}
});
});
});
Please help me out :)
You know that html forms can send arrays, right?
<input type="text" name="textelement[]" value="First Element" /><br/>
<input type="text" name="textelement[]" value="Second Element" /><br/>
PHP Code:
foreach($_POST['textelement'] as $somethingSomething){
echo $somethingSomething, "\n";
}
Prints out:
First Element
Second Element
add a class to to action buttons and pass the comment id as data attribute like so:
<a class="commentBtn" href='' data-commentid="1">Comment</a>
and than you can read out the id easily with jquery:
$(".commentBtn").live("click",function(e){
var id = $(this).data('commentid');
e.preventDefault();
// do something with id…
});