A
A
Alexander Gorkin2018-07-24 23:31:58
JavaScript
Alexander Gorkin, 2018-07-24 23:31:58

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('Ошибка');
                }
            });
        });

Which cancels the transition by the link, and displays the id value in the console.
The button itself:
<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>


But after clicking, it still follows the link to another page.

Answer the question

In order to leave comments, you need to log in

3 answer(s)
@
@kotmail, 2018-07-24
@mrbagfreeman

Correct the class name. In JS you have "add_to_cart", and on the button "add-to-cart".

V
Viktor Yanyshev, 2018-07-24
@villiwalla

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.

V
Vladimir Proskurin, 2018-07-24
@Vlad_IT

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 question

Ask a Question

731 491 924 answers to any question