When clicking the button makes two ajax requests, how to avoid?

Asked

Viewed 511 times

1

When I click on the "Hire" button it makes two requests on the server at once, as I can 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);
        }
    });
});
  • There will only be two requests if there are two clicks or if you have entered twice the callback of the event. This is what is happening?

  • There are no two clicks, I just click once and it makes two requests, it seems that it is entering twice in the callback

  • The element with the class .pagar is created dynamically? Because it is only justified the use of on in the document..

  • Yes, I am creating several buttons that will do the same thing. I gave console.log(this); and it returns me the button twice..

  • Not tested, but try to see if there is no propagation problem. https://api.jquery.com/event.stoppropagation/

1 answer

2


Put your code in 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 in the creation like this :

<input onclick="teste(this)">

or

$('input').attr('onclick','teste(this)');
  • This will work if the element has not been generated dynamically.

  • This does not work in my case, I am generating several buttons that will do the same thing. (Note: already tested)

  • I changed the answer, see if it works.

  • It worked haha, thank you very much!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.