Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

185
Visualizações
How can I simplify my javascript and ajax calls?

I am having a couple of buttons for a demo application

<div style="margin-top: 10px;" class="text-center">
    <h3>Events</h3>
    <button id="trackTrace" class="btn btn-warning">TrackTrace()</button>
    <button id="trackException" class="btn btn-warning">TrackException()</button>
    <button id="trackEvent" class="btn btn-warning">TrackEvent()</button>
</div>

Now I would like to issue AJAX calls when one of the buttons is clicked. I solved this as follows.

<script>
    $("#trackTrace").click(function () {
        $.ajax({
            url: "/api/event/trace",
            type: "GET",
            success: function (result, status, xhr) {
                $("#message").text("Success").show();
            },
            error: function (xhr, status, error) {
                $("#error").text("Error").show();
            }
        })
    });

    ... 
</script>

This however seems to break the DRY principle, I don't want to repeat that for every button. Sure I could move the displaying of the text into a separate function.

However, the following calls showError() and showSuccess() even if the AJAX call was fine.

function showSucess(result, status, xhr) {
    $("#message").text("Success").show();
};

function showError(xhr, status, error) {
    $("#error").text("Exception thrown on Backend-API!").show();
};

$("#trackTrace").click(function () {
    $.ajax({
        url: "/api/event/trace",
        type: "GET",
        success: showSucess(),
        error: showError()
    })
});

So how can I simplify my code? I am looking for a switch like way that acts upon button clicks.

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

  1. Event handlers need to not have the () when used in an assignment success: showSuccess, - OR it has to return a function
  2. Delegation is built into JS and jQuery
$("#eventContainer .track").on("click", function () {
    $.ajax({
        url: "/api/event/" + this.dataset.url,
        type: "GET",
        success: showSucess,
        error: showError
    })
})
<div id="eventContainer" style="margin-top: 10px;" class="text-center">
    <h3>Events</h3>
    <button id="trackTrace" class="track btn btn-warning" data-url="tracktrace">TrackTrace()</button>
    <button id="trackException" class="track btn btn-warning" data-url="trackexception">TrackException()</button>
    <button id="trackEvent" class="track btn btn-warning" data-url="trackevent">TrackEvent()</button>
</div>
about 4 years ago · Juan Pablo Isaza Relatório

0

HTML:

<div style="margin-top: 10px;" class="text-center">
    <h3>Events</h3>
    <button data-url="/api/event/trace" class="btn btn-warning">TrackTrace()</button>
    <button data-url="/api/event/exception" class="btn btn-warning">TrackException()</button>
    <button data-url="/api/event/event" class="btn btn-warning">TrackEvent()</button>
</div>

JS:

$("button[data-url]").each(function () {
    const clickedElement = this;
    $(this).click(function () {
      $.ajax({
          url: clickedElement.dataset.url,
          type: "GET",
          success: function (result, status, xhr) {
              $("#message").text("Success").show();
          },
          error: function (xhr, status, error) {
              $("#error").text("Error").show();
          }
      })
  });
});

Note that you don't need to assign id to your buttons. Also I'm not 100% sure syntax is correct as I haven't worked with jQuery for a while

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda