Clicking the button makes two ajax requests, how to avoid it?

1

When I click the "Hire" button it makes two requests on the server at once, how can I avoid this?

<button type="button" class="pagar" id="10.00">Contratar</button>

Ajax

$(document).on('click', ".pagar", function () {
    preco = $(this).attr('id');
    $.ajax({
        url: path + 'Usuario/efetuarPagamento',
        type: 'POST',
        data: {preco: preco},
        success: function (response) {
            console.log(response);

        }, error: function () {
            console.log(erro, er);
        }
    });
});
    
asked by anonymous 26.06.2017 / 22:12

1 answer

2

Place your code on a function:

function teste(e){
 preco = $(e).attr('id');
 $.ajax({
    url: path + 'Usuario/efetuarPagamento',
    type: 'POST',
    data: {preco: preco},
    success: function (response) {
        console.log(response);

    }, error: function () {
        console.log(erro, er);
    }
 });
}

And whenever you create a new button you add the attr or directly into the creation like this:

<input onclick="teste(this)">

or

$('input').attr('onclick','teste(this)');
    
26.06.2017 / 22:22