-1

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.

Matthias Güntert
  • 4,013
  • 6
  • 41
  • 89
  • 1
    Do "success: showSucess, error: showError" without the parentheses. You want a function "pointer", not to call it immediately. – Rani Sharim Oct 12 '21 at 10:17
  • _"However, the following calls `showError()` and `showSuccess()` even if the AJAX call was fine"_ - This has nothing to do with the title. Calling a function is not the same as using a function as object. -> (Possible dupe) [Why is the method executed immediately when I use setTimeout?](https://stackoverflow.com/questions/7137401/why-is-the-method-executed-immediately-when-i-use-settimeout) – Andreas Oct 12 '21 at 10:18
  • _"I am looking for a switch like way that acts upon button clicks."_ - Why a `switch`? – Andreas Oct 12 '21 at 10:20

2 Answers2

1
  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>
mplungjan
  • 169,008
  • 28
  • 173
  • 236
1

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

NoOorZ24
  • 2,914
  • 1
  • 14
  • 33