Answer the question
In order to leave comments, you need to log in
ajax function not working. How to be?
In Yii, I wrote the following function for the button:
$('.add_to_cart').on('click', function (e) {
e.preventDefault();
var id = $(this).data('id');
$.ajax({
url: '/cart/add',
data: {id: id},
type: 'GET',
success: function(res){
if (!res) aler('ошибка!');
console.log(res);
//showCart(res);
},
error: function(){
alert('Ошибка');
}
});
});
<a class="add-to-cart" data-id="<?= $product->id?>" href="<?= \yii\helpers\Url::to(['/cart/add', 'id' => $product->id])?>"><button class="btn btn-choose">Выбрать</button></a>
Answer the question
In order to leave comments, you need to log in
Correct the class name. In JS you have "add_to_cart", and on the button "add-to-cart".
Doesn't it bother you that there is no alert and there is nothing in the console? Watch how you separate words by naming a class and passing it to the jq selector.
Everything should work https://jsfiddle.net/a49f3nzu/ see console for errors.
Or, if your code is executed before a link appears on the page, try wrapping it in $(function() { })
$(function() {
$('.add_to_cart').on('click', function (e) {
e.preventDefault();
var id = $(this).data('id');
$.ajax({
url: '/cart/add',
data: {id: id},
type: 'GET',
success: function(res){
if (!res) aler('ошибка!');
console.log(res);
//showCart(res);
},
error: function(){
alert('Ошибка');
}
});
});
});
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question