dynamic button(s) (generate by ajax ) not clickable - javascript

i try to create a shop cart using ajax (add working 100% )
but when i try to remove item(s) i found button not clickable
this is the code of delete :
$(document).on('click', '.delete', function() {
var product_id = $(this).attr("id");
var action = "remove";
console.log('something'); // show nothing
$.ajax({
url: "action.php",
method: "POST",
dataType: "json",
data: {
product_id: product_id,
action: action
},
success: function(data) {
$('#order_table').html(data.order_table);
$('#order_footer').html(data.order_footer);
$('.badge').text(data.cart_item);
}
});
})
Button code :
<button class="text-danger delete" id="<?php echo $values["product_id"]; ?>" >
<i data-feather="x"></i>
</button>

Related

Ajax call to change icons

I created below button
<button id="wishbtn" data-slug='{{ list.slug }}'><i class="far fa-heart"></i></button>
which calls an Ajax call.
$(document).on('click', '#wishbtn', function (e) {
let el = $(this);
$.ajax({
type: 'GET',
url: "{% url 'listing:wishlist' %}",
data: {
title_slug: el.attr("data-slug"),
},
success: function () {
alert('added to wishlist');
}
})
});
How do I change the class of i tag to fas fa-heart once the button is clicked. I tried using this keyword in success function to change its class $(this).classList.replace('far', 'fas') but it didn't work. I tried using e.target.getElementsByTagName('i')[0].classList.replace('far', 'fas') and again no hope.
Can you help me please, thank you.
$(document).on('click', '#wishbtn', function(e) {
let el = $(this);
$.ajax({
type: 'GET',
url: "{% url 'listing:wishlist' %}",
data: {
title_slug: el.attr("data-slug"),
},
success: function() {
let li = el.find('li')
li.removeClass('far')
li.addClass('fas')
}
})
});

Creating an if in a js function

This is a code that filter all order history the user have but a want to create an if to just filter only the orders that I bought online (I have a variable that is 1 if is in the store and 2 if is online). How to i do the if?
filterOrderHistory: function() {
$(".historyorder-state").on('click', function(){
$('#filterOptions').show();
});
$('#filterOptions li').on('click', function() {
var text = $(this).text();
$('.tbl-shopping-history').html('<div class="form-spinner"><i class="fa fa-spinner fa-spin"></i></div>');
$.ajax({
method: "GET",
data: { state: $(this).attr('class').toUpperCase() },
dataType: "html",
url: '/impuls/store/components/order-history-table.jspf'
})
.done(function(data) {
$('.tbl-shopping-history').html(data);
$('.historyorder-state').html(text+'<i class="fa fa-caret-down"></i>');
$('#filterOptions').hide();
});
});
}
};

Update javascript variables after ajax call

I'm attempting to dynamically update a notice after the cart is updated via ajax. I can't seem to figure out how to re-update all variables so the calculation loop could run again. I tried wrapping the if statement into a function and calling that again inside of updated_wc_div but that didn't work.
Any suggestions?
( function($) {
var membership_price = membership.price;
//grab cart total from html
var total = parseInt($('.order-total .woocommerce-Price-amount').text().replace('$',''));
compared_price = parseInt(membership_price) - total;
//everything runs fine on load.
if ( total < membership_price ) {
message = 'For <strong>$'+ compared_price +'</strong> more, gain access to unlimited downloads. Become a member!';
notice = '<div class="woocommerce-info">' + message + '</div>';
$('.woocommerce-notices-wrapper').html(notice);
}
//running this to know when ajax is called
$(document.body).on('updated_wc_div',function( event ){
$('.woocommerce-notices-wrapper').empty();
total = parseInt($('.order-total .woocommerce-Price-amount').text().replace('$',''));
//I believe problem is here, it doesn't update variable so it could loop again.
});
} )(jQuery);
this is how I dynamically update an object after ajax call is being called:
function getCart(user_id) {
$.ajax({
type: "POST",
url: "get_total_cart.php",
data: {
'user_id': <?php echo $user_id; ?>
},
beforeSend: function() {},
success: function(response) {
var user = JSON.parse(response);
var total_cart = parseInt(user.total_cart);
$("#total_cart").html(total_cart);
}
});
}
function addCart(product_id, user_id) {
$.ajax({
type: "POST",
url: "add_cart.php",
data: {
'product_id': product_id,
'user_id': user_id
},
beforeSend: function() {},
success: function(response) {
getCart(user_id);
}
});
}
$(document).ready(function() {
$(".se-pre-con").fadeOut("slow");
getCart(<?php echo $user_id; ?>);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="total_cart">Total Cart</div>
<input type="button" name="add_cart" id="add_cart" value="Add to Cart" onclick="addCart('<?php echo $product[id]; ?>', '<?php echo $user_id; ?>')" class="btn btn-info">
I hope this helps.
Cheers.
Simply you have to put your function inside the ajax function or make the ajax function "async:false"
$.ajax({
type: "POST",
url: "",
async:false, // <======== remove asynchronous property
data: {},
success: function(result) {
}
});
////////////////////////////////////////////////
$.ajax({
type: "POST",
url: "",
data: {},
success: function(result) {
// Or put your function here
}
});

AJAX and Codeigniter - Determining what button has been pressed to update

I have this shopping cart wherein I can add or subtract the quantity of a specific item. The problem is I don't know how to determine if the user has pressed the plus button or the minus button.
HTML code of the plus/minus
<td>
<div class="input-group" style="width: 100px !important;">
<span class="input-group-btn">
<button class="btn btn-danger btn-minus" type="button">-</button>
</span>
<input class="form-control table-shopping-qty" type="text" id = "<?php echo $cartrow['id']?>" value="<?php echo $cartrow['qty']?>" style="padding-left:5px;text-align: center;"/>
<span class="input-group-btn">
<button class="btn btn-success btn-plus" type="button">+</button>
</span>
</div><!-- /input-group -->
</td>
AJAX Function
function updateShoppingCart(){
var productid = $(".table-shopping-qty").attr("id");
dataString = {productid: productid};
$.ajax({
type: "POST",
url: "<?php echo base_url(); ?>"+"listproductscontroller/editcart_item",
data: dataString,
cache: false,
success: function(){
swal('Success!', 'Cart updated!', 'success');
}, error: function(){
swal('Oops!', 'Something went wrong. Please try again later', 'error');
}
});
}
Controller
public function editcart_item(){
$id = $this->input->post('productid');
if($this->session->userdata('cartsession')){
$cartsession = $this->session->userdata('cartsession');
foreach($cartsession as $row){
if($row['id'] == $id){
$updated = array('id'=>$row['id'], 'qty'=>$row['qty'] - 1);
}else{
$updated = array('id'=>$row['id'], 'qty'=>$row['qty']);
}
}
$this->session->set_userdata('cartsession', $updated);
}
if($this->session->userdata('cartsession')!=NULL){
if($this->cartdata = $this->ProductModel->getProductToCart($this->session->userdata('cartsession'))){
$this->session->set_userdata('globalcart', $this->cartdata);
}
}
}
load url helper in controller.using $this->load->url('url');.Then
function updateShoppingCart(){
var productid = $(".table-shopping-qty").attr("id");
dataString = {productid: productid};
$.ajax({
type: "POST",
url: "<?php echo base_url('listproductscontroller/editcart_item');?>",
data: dataString,
cache: false,
success: function(data){
alert("success");
}, error: function(){
alert("failed");
}
});
Don't forget to set
$_config['base_url'] ="your_domain_name";

$this->input->post() is always empty in codeigniter

I am trying to get a value from an AJAX post that always seems to be empty. I already tried printing the value before doing the post and it works fine but I cannot get the value via $this->input->post()
HTML
<?php if ($product_info->stock > '1'){?>
<button class="btn btn-lg btn-primary" product_id = "<?php echo $product_info->id;?>" id = "addtocart"><i class="fa fa-shopping-cart"></i>Add to Cart</button><?php}?>
Javascript
$(document).ready(function(){
$("#addtocart").click(function(){
var productid = $(this).attr('product_id');
$.ajax({
type: "POST",
url: "<?php echo base_url();?>shoppingcart",
data: productid,
cache: true,
success: function(productid){
$("#cartstatus").html('<div class="alert alert-success"><strong>Success! </strong>Item has been added to the cart.</div>');
}, error: function(productid){
$("#cartstatus").html('<div class="alert alert-danger"><strong>Opps! </strong>Something went wrong.</div>')
}
});
});
});
Controller
$productcart = array();
if($this->session->userdata('cartsession')){
$cartsession = $this->session->userdata('cartsession');
foreach($cartsession as $id=>$val){
$productcart[$id] = $val;
}
}
$productcart[$this->input->post('productid')] = 50; -->sample value
$this->session->set_userdata('cartsession', $productcart);
$cartsession = $this->session->userdata('cartsession');
data params have certian format for sending values to the server using ajax.
Try this ...
$(document).ready(function(){
$("#addtocart").click(function(){
var productid = $(this).attr('product_id');
$.ajax({
type: "POST",
url: "<?php echo base_url();?>shoppingcart",
data: {productid : productid},
cache: true,
success: function(productid){
$("#cartstatus").html('<div class="alert alert-success"><strong>Success! </strong>Item has been added to the cart.</div>');
}, error: function(productid){
$("#cartstatus").html('<div class="alert alert-danger"><strong>Opps! </strong>Something went wrong.</div>')
}
});
});
});
Instead having your own attribute 'product-id', use HTML5's data attribute like 'data-product_id', so the HTML code looks like:
<button class="btn btn-lg btn-primary" data-product_id="<?php echo $product_info->id;?>" id="addtocart"><i class="fa fa-shopping-cart"></i>Add to Cart</button><?php}?>
Also, assign class name to the elements if you have more than one 'Add to Cart' buttons to group them, so it looks like:
<button class="btn btn-lg btn-primary" data-product_id="<?php echo $product_info->id;?>" class="addtocart"><i class="fa fa-shopping-cart"></i>Add to Cart</button><?php}?>
It's time to make use of the data attribute using jQuery:
var product_id = $(this).data('product_id');
Now, the whole code looks like
$(document).ready(function(){
$(".addtocart").click(function(){
var product_id = $(this).data('product_id');
$.ajax({
type: "POST",
url: "<?php echo base_url();?>shoppingcart",
data: product_id,
cache: true,
success: function(response){
$("#cartstatus").html('<div class="alert alert-success"><strong>Success! </strong>Item has been added to the cart.</div>');
}, error: function(response){
$("#cartstatus").html('<div class="alert alert-danger"><strong>Oops! </strong>Something went wrong.</div>')
}
});
});
});
Hope it works.

Categories