I am trying to get rid of the redirect/reload when the user is adding a product or gets a info message in my woocommerce shop. I just want to show the "added to cart" message in a tooltip or overlay div and let them continue shopping without renavigate to the shop.
AJAX add to cart is enabled
so my question is:
what can I do to display this messages without refreshing the whole page?
EDIT: maybe useful for anyone, heres my FINAL CODE:
$('.add_to_cart_button, .single_add_to_cart_button').click(function(e) {
var produkt_id;
if ($(this).attr('data-product_id') == undefined) {
produkt_id = $('input[type=hidden]').val();
} else {
produkt_id = $(this).attr('data-product_id');
}
var amount;
if ($(this).hasClass('single_add_to_cart_button') == true) {
if ($('.qty').val() !== '1') {
amount = $('.qty').val();
}
console.log(amount + ' single_add_to_cart_button');
}
else {
amount = '1';
console.log(amount + ' add_to_cart_button');
}
function addToCart(produkt_id) {
$.ajax({
type: 'POST',
url: '?add-to-cart=' + produkt_id,
data: {'product_id': produkt_id,
'quantity': amount},
success: function(response, textStatus, jqXHR) {
// callback
}/*,
dataType: 'JSON'*/
});
}
e.preventDefault();
addToCart(produkt_id);
});
Do you mean something like this:
if you do the function "addedToChart" it will do a ajax and creat a message at top of the page
$(document).on('click','.add_to_cart_button',function(e) {
e.preventDefault();
addedToCart($(this).data('product_id'));
});
function addedToCart(id){
$.ajax({
type: "POST",
url: "some.php",
data: { product_id: id},
success: function(){
$('body').prepend('<div style="position:fixed; height:20px; width:100%; background-color:red; text-align:center;">Added to chart</div>');
}
});
}
Related
I'm trying to get a value from my database and then run an update using sweet alert pop-up but it is not working. The alert seem to pop-up and once the value is entered, it displays the value entered but not working. below is my actual ajax code:
viewproduct.php
<script>
$(document).ready(function() {
$('.btnupdatestock').click(function() {
var id = $(this).attr("id");
//var new_stock = $(this).val();
swal("Add Stock:", {
content: "input",
})
.then((updateStock) => {
$.ajax({
type: 'POST',
url: 'stock-in.php',
data:{
stock_up: updateStock,
},
success: function(data){
swal(`Updated: ${updateStock}`);
},
error: function(data){
swal(`Error updating: ${updateStock}`);
}
});
});
});
});
</script>
the above method was designed to trigger sql in stock-in.php and the code in stock-in.php is below:
<?php
include_once'connectdb.php';
if($_SESSION['useremail']=="" OR $_SESSION['role']=="Admin"){
header('location:index.php');
}
$idd=$_GET['id'];
$select=$pdo->prepare("select * from tbl_product where pid=$idd");
$select->execute();
while($row=$select->fetch(PDO::FETCH_OBJ)){
$productName = $row['pname'];
$oldstock = $row['pstock'];
//$id=$_POST['uid'];
$stockup=$_POST['stock_up'];
alert('I clicked');
$new_stock = $oldstock + $stockup;
$sql="UPDATE `tbl_product` SET `pstock` = ? WHERE pid= ? ";
$update=$pdo->prepare($sql);
$update->execute([$new_stock, $idd]);
if($result){
echo'Stock updated!';
}else{
echo'Error in updating stock';
}
}
?>
below is a picture of my UI that shows pop-up but it's not updating.
This is what I intend to do: If a user clicks on update and enters a value say 50, it should retrieve the old stock (database, say 100) and add to the new stock (value entered, say 50) and then update the database with 150. I am stuck here and any help would be appreciated. Thanks.
$(document).ready(function() {
$('.btnupdatestock').click(function() {
swal("Add Stock:", {
buttons: true,
closeModal: true,
content: "input",
}).then((updateStock) => {
if (updateStock === "") {
swal("You need to write something!");
return false
}else{
$.ajax({
type: 'POST',
url: 'stock-in.php',
data:{
stock_up: updateStock
<?php
echo ', id: '.$row->pid.' '
?>
<?php
echo ', oldstock: '.$row->pstock.' '
?>
},
success: function(data){swal(`Updated: ${updateStock}`);},
error: function(data){swal(`Error updating: ${updateStock}`);}
});
}
});
});
});
The major issue I had was I didn't make the SQL query global at the top of my page and then applied '.$row->pid.'
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.
Livesearch result is coming absolutely fine with add to cart button properly.
When for the first time I add any product into cart, that replaces value of cart in header file & also replaces 'Add to Cart' button to 'Added'.
When for the second time I add product to cart with the SAME SEARCH RESULT, it updates value of button to 'Added' but it doesn't update the value of cart in my header. So this is the issue.
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?
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>
I have this ajax-loaded #container and I'm trying to get it to play nice with some of my plugins. So far I managed to get scrollTo and a lightbox working inside this "container of death" using jquery.live but no luck with my fancy "add to cart" buttons. I've been playing around with .delegate, the livequery plugin, etc., for a few days now but I'm really not advanced enough to figure out what goes where. (I have a pretty shallow understanding of what I'm doing.)
Here's my shopping cart plugin, it's fairly small and straightforward. Can you give suggestions on what (.live, .delegate, or .livequery, or perhaps something else entirely) should be inserted where?
(Note: shopme p = the add to cart buttons, which need to be inserted inside the ajax-loaded "container of death." The rest of the cart exists outside said container and works fine since it's not ajax'ed in.)
$(document).ready(function(){
$('.wooo').bloooming_shop();
$('body').append('<div id="panel"><div id="panelcontent"></div><div class="panelbutton" id="hidepanel" style="display: none;"><a><font class="cartfont2">hide cart</font></a></div></div><div id="showpanel" class="panelbutton" style="display: visible;"><a><font class="cartfont">shopping cart</font></a></div><div id="btntarget"></div>');
$('#panelcontent').hide();
$.ajax({
type: "GET",
url: "/wooo/cart.php",
async: false,
dataType: "html",
success: function(html){
$('#panelcontent').html(html);
}
});
$(".panelbutton").click(function(){
$("#panel").animate({
height: "200px"
}, "fast",function(){
$('#panelcontent').show();
});
$("#hidepanel").fadeIn();
$("#showpanel").fadeOut();
});
$("#hidepanel").click(function(){
$("#panel").animate({
height: "0px"
}, "fast", function(){
$("#showpanel").fadeIn();
$('#panelcontent').hide();
});
$("#hidepanel").fadeOut();
});
// START 'ADD TO CART' BUTTONS
$('.shopme p').click(function(){
var pid = $(this).attr('rel');
$('body').prepend('<div class="shadow" id="'+$(this).attr('rel')+'_shadow"></div>');
var shadow = $('#'+pid+'_shadow');
shadow.width($(this).parent().css('width')).height($(this).parent().css('height')).css('top', $(this).parent().offset().top).css('left', $(this).parent().offset().left).css('opacity', 0.5).show();
shadow.css('position', 'absolute');
shadow.animate( {
width: $('#btntarget').innerWidth(),
height: $('#btntarget').innerHeight(),
top: $('#btntarget').offset().top,
left: $('#btntarget').offset().left
}, {
duration: 2000
} )
.animate({
opacity: 0
},
{
duration: 700,
complete: function(){
shadow.remove();
}
});
var option = $('#'+pid+' .woooptions').val();
var formData = 'pid=' + pid + '&option=' + option;
$.ajax({
type : 'POST',
url : '/wooo/cart.php',
data : formData,
success : function (html) {
$('#panelcontent').html(html);
}
});
});
$('.removeitem').live('click', function() { // .LIVE is used here
rid = $(this).attr('id');
rop = $(this).attr('rel');
var remData = 'remove=' + rid + '&rop=' + rop;
$.ajax({
type : 'POST',
url : '/wooo/cart.php',
data : remData,
success : function (html) {
$('#panelcontent').html(html);
// alert('thx');
}
});
});
}); // document
function checkOut(){
jQuery.ajax({
url: "/wooo/cart.php",
type: "POST",
data : "destroysession=true",
success: function(data, textStatus, jqXHR){
if(data){
window.location.href=jQuery('a.checkout').attr("data-href");
}else{
console.log("There is no data!")
}
},
error: function(jqXHR, textStatus, errorThrown){
console.log("AJAX ERROR: "+errorThrown)
}
});
}
/** replace ******/
jQuery.fn.bloooming_shop = function(){
this.each(function(){
var elem = $(this);
var cl = 'bt1';
var id = $(this).html();
var opt = $(this).attr('options');
var text = $(this).attr('text');
var price = $(this).attr('price');
// alert(price);
if (text == undefined) {
text = 'add to cart';
}
if (opt == 'true' && price != 'true' ) {
cl = 'bt3';
}
if (price == 'true' && opt == 'true') {
cl = 'bt4';
}
if (price == 'true' && opt != 'true') {
cl = 'bt2';
}
elem.removeClass('wooo');
elem.addClass('shopme');
elem.addClass(cl);
elem.attr('id','pid'+id);
elem.html('<p rel="pid'+id+'" class="'+cl+'">'+ text +'</p>');
// get product data
if (price == 'true' || opt == 'true') {
$.ajax({
type : 'GET',
url : '/wooo/functions.php?mode=p_data&id='+id+'&opt='+opt+'&price='+price,
success : function (html) {
elem.append(html);
if (jQuery().sSelect) {
elem.children('.woooptions').sSelect();
}
// change price
$('.woooptions').change(function(){
var selid = $(this).attr('id');
var rel = $('#'+selid+' option:selected').attr('rel');
if (rel != undefined) {
$(this).parent().children('.woooprice').html(rel);
}
});
}
});
}
});
return false;
};
How do I keep this plugin alive, even within ajax'ed-in #container? I really just need the 'add to cart' buttons (shopme p) to be in said container div. Thank you.
.live("click", function(){
instead of just click.
Hi im currently developing this site:
http://remedia-solutions.com/clientes/0039_kiplingmexico/demo2/
its almost done but im currently having some troubling on a section "Coleccion" in this section the first thing you do is select a specific type of bags , once you select it, you will get only 20 bags loaded (this bags are loaded from a mysql db) when you get to the bottom of the page it will show another 20 bags. Now the problem here is that when i get to the bottom the JS function runs like 5 times :/ So is there a way it only run once then wait a bit and run it again?
Heres my Jquery code
Once you click a "Coleccion" it will do this:
$("#coleccionmenu span").click(function() {
$("#coleccionmenu span").removeClass('focuscoleccion')
$(this).addClass('focuscoleccion');
$("#contbolsas").fadeOut('fast')
var id = this.id;
$.ajax({
url: "respuestabolsas.php",
type: "POST",
data: "id=" + id,
complete: function() {
//called when complete
},
success: function(x) {
$("#contbolsas").css("display", "none");
$("#contbolsas").html(x)
$(".bolsacargada").css('opacity', '0');
$("#contbolsas").css("display", "block");
$(".bolsacargada").each(function(index) {
$(this).delay(300*index).animate({opacity: 1}, 400);
});
hovercolores();
if ($('#contbolsas > div:contains("Rawr")').length > 0) {
$("#text").fadeOut()
return false;
}
else{
$("#text").fadeIn()
cargamascoleccion(id)
}
},
error: function() {
//called when there is an error
},
});
});
Once is loaded i need the id from the collection you just clicked so when you scroll down it only show those collections and not the other ones:
function cargamascoleccion(id){
$("#todocoleccion").scroll(function() {
var bottom = $("#todocoleccion").scrollTop() - $(window).height();
if( bottom > $(".bolsacargada:last").offset().top + 300 ){
$.ajax({
url: "respuestabolsas2.php",
type: "POST",
data: "id=" + id + "&idultimabolsa=" + $(".bolsacargada:last").attr('id'),
complete: function() {
//called when complete
},
success: function(x) {
hovercolores();
if(x != ""){
$("#contbolsas").append(x)
}
else{
$("#text").fadeOut()
return false;
}
},
error: function() {
//called when there is an error
},
});
}
});
}
I doubt theres a problem on the php code i think the problem is on the function above cause it runs like 4 times when i get to the offset of the last bag. Any ideas?
It looks like its firing the ajax call multiple times because the condition is met multiple times while the user is scrolling. You might want to add another condition to the if statement before executing the ajax call which checks whether it has already been initiated. Something along the lines of
var ajaxComplete = true;
$("#todocoleccion").scroll(function() {
var bottom = $("#todocoleccion").scrollTop() - $(window).height();
if (bottom > $(".bolsacargada:last").offset().top + 300 && ajaxComplete) {
$.ajax({
url: "respuestabolsas2.php",
type: "POST",
data: "id=" + id + "&idultimabolsa=" + $(".bolsacargada:last").attr('id'),
beforeSend: function() {
ajaxComplete = false
},
complete: function() {
//called when complete
ajaxComplete = true;
},
success: function(x) {
hovercolores();
if (x != "") {
$("#contbolsas").append(x)
}
else {
$("#text").fadeOut()
return false;
}
},
error: function() {
//called when there is an error
},
});
}
});
My page consists of a list of records retrieved from a database and when you click on certain span elements it updates the database but at present this only works for the first record to be displayed.
(Basically changes a 0 to 1 and vice versa)
These are my two html elements on the page that are echoed out inside a loop:
Featured:<span class="featured-value">'.$featured.'</span>
Visible:<span class="visible-value">'.$visible.'</span>
Here is what I have:
$(document).ready(function() {
$('.featured-value').click(function() {
var id = $('.id-value').text();
var featured = $('.featured-value').text();
$('.featured-value').fadeOut('slow');
$.ajax({
type: "POST",
url: "process.php",
data: "id="+id+"&featured="+featured,
success: function(data) {
$('.featured-value').html(data);
$('.featured-value').fadeIn('slow');
}
});
return false;
});
// same function for a different span
$('.visible-value').click(function() {
var id = $('.id-value').text();
var visible = $('.visible-value').text();
$('.visible-value').fadeOut('slow');
$.ajax({
type: "POST",
url: "process.php",
data: "id="+id+"&visible="+visible,
success: function(data) {
$('.visible-value').html(data);
$('.visible-value').fadeIn('slow');
}
});
return false;
});
});
It was working fine with one using id attributes but now I'm using class the fadeIn part of the success query isn't working but I'm hoping the .each will fix this.
UPDATE
The full loop is as follows:
while ($event = $db->get_row($events, $type = 'MYSQL_ASSOC'))
{
// open event class
echo '<div class="event">';
echo '<div class="id"><span class="row">Event ID:</span><span class="id-value"> '.$id.'</span></div>';
echo '<div class="featured"><span class="row">Featured: </span><span class="featured-value">'.$featured.'</span></div>';
echo '<div class="visible"><span class="row">Visible: </span><span class="visible-value">'.$visible.'</span></div>';
echo '</div>';
}
Cymen is right about the id selector causing you trouble. Also, I decided to refactor that for you. Might need some tweaks, but doesn't everything?
function postAndFade($node, post_key) {
var id = $node.parents('.id').find('.id-value').text();
var post_val = $node.text();
$node.fadeOut('slow');
$.ajax({
type: "POST",
url: "process.php",
data: "id="+id+"&"+post_key+"="+post_val,
success: function(data) {
$node.html(data);
$node.fadeIn('slow');
}
});
return false;
}
$('.featured-value').click(function() { return postAndFade($(this), 'featured'); });
$('.visible-value').click(function() { return postAndFade($(this), 'visible'); });
The click function is getting the same id and value on each click because you've bound it to the class. Instead, you can take advantage of event.target assuming these values are on the item being clicked. If not, you need to use event.target and navigate to the items within the row.
$('.featured-value').click(function(event) {
var $target = $(event.target);
var id = $target.attr('id');
var featured = $target.text();
$target.fadeOut('slow');
$.ajax({
type: "POST",
url: "process.php",
data: "id="+id+"&featured="+featured,
success: function(data) {
$target.html(data).fadeIn('slow');
}
});
return false;
});
So something like that but it likely won't work as it needs to be customized to your HTML.