Reputation: 1065
I've header.php file in which I've code to do livesearch. In that search, I've directly included 'Add to Cart' button so that user can directly add products through search only. I've Cart div in my header file in which I display number of items in cart.
Here's my code:
HEADER.PHP
<script type="text/javascript">
$(document).ready(function()
{
$(".searchproductbrand").keyup(function()
{
var kw = $(".searchproductbrand").val();
if(kw != '')
{
$.ajax
({
type: "POST",
url: "livesearch.php",
data: "kw="+ kw,
success: function(option)
{
$("#livesearch").show();
$("#livesearch").html(option);
document.getElementById("livesearch").style.border="1px solid #A5ACB2";
}
});
}
else
{
$("#livesearch").html("");
document.getElementById("livesearch").style.border="0px";
}
return false;
});
$(document).delegate('.buynow','click', function(){
var productid = $(this).attr('id');
var quantity = $('#quantity_'+productid).val();
var type= $('#type_'+productid).val();
$.ajax({
type: "POST",
url: "db_addtocart.php",
context: this,
data: {quantity:quantity,
type:type,
productid:productid},
success: function(option){
this.value = 'Added';
$('#carttotal').empty();
$('#carttotal').replaceWith(option);
}
});
return false;
});
});
</script>
<div id='carttotal'><input type='button' class='button' id='cartdetails'
value='<?php echo "Cart (".$proInCart.")"?>' style='padding:7px;
border-radius:15px;'></div>
For an example if I search for 'he' it displays 14 results. For first result, if I click on 'Add to Cart' button, it changes the value of this button to 'Added' & update the Cart div. But from second request with the same search result, it doesn't update the cart however it updates the value of button to 'Added'.
Why is that? Can anyone help?
Upvotes: 1
Views: 86
Reputation: 6075
The reason your code is not working after the first request is that you are returning false at the end of the functions. You should change your function into something like:
<script type="text/javascript">
$(document).ready(function()
{
$(".searchproductbrand").keyup(function(e)
{
var kw = $(".searchproductbrand").val();
if(kw != '')
{
$.ajax
({
type: "POST",
url: "livesearch.php",
data: "kw="+ kw,
success: function(option)
{
$("#livesearch").show();
$("#livesearch").html(option);
document.getElementById("livesearch").style.border="1px solid #A5ACB2";
}
});
}
else
{
$("#livesearch").html("");
document.getElementById("livesearch").style.border="0px";
}
e.preventDefault();
});
$(document).delegate('.buynow','click', function(e){
var productid = $(this).attr('id');
var quantity = $('#quantity_'+productid).val();
var type= $('#type_'+productid).val();
$.ajax({
type: "POST",
url: "db_addtocart.php",
context: this,
data: {quantity:quantity,
type:type,
productid:productid},
success: function(option){
this.value = 'Added';
$('#carttotal').empty();
$('#carttotal').replaceWith(option);
}
});
e.preventDefault();
});
});
</script>
Upvotes: 1