Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

181
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda