Home > front end >  How can I simplify my javascript and ajax calls?
How can I simplify my javascript and ajax calls?

Time:10-13

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.

CodePudding user response:

  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>

CodePudding user response:

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

  • Related