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.