F
F
frontend-front2018-09-12 11:45:21
JavaScript
frontend-front, 2018-09-12 11:45:21

Product IDs not being added to json ajax?

When I click on the button, I try to pass the id of this product and send an ajax request. Ajax should give me json
and whether there is already such an id or not. But ajax throws an error, it doesn't like dataType: "json".
https://codepen.io/anon/pen/LJdvgQ

$(function () {
  var arr = [];
    $(document).on('click', '.product-btn', function (event) {
        event.preventDefault();

        var id_product = $(this).data("id");
        arr.push(id_product);

       $.ajax({
            type: 'POST',
            url: 'ajax.php',
            contentType: 'application/json',
            data: JSON.stringify(arr),
            dataType: "json",
            success: function (data, id_product) {
            	
                        if(arr.indexOf(id_product) != -1){ 
                                    alert("Такой товар уже существует");
                        } else {
                                    arr.push(id_product);
                                    alert("Товар успешно добавлен");
                        }
             },
            error: function (data) {
                console.error("Ошибка при работе с избранным");
            }
        });

    });
});

Answer the question

In order to leave comments, you need to log in

1 answer(s)
I
Isherath, 2018-09-12
@Isherath

Try making var arr = [] - an array, not an object var arr = {} like you have now.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question