I have a button on a page that calls an API. The button allows you to follow a user or stop following.
Clicking the button changes a label that is next to the button and the symbol on the button.
The problem is that sometimes everything works well and others do not. I did debug and realized that when failure is because the value goes null to the API. The strangest thing is that when you get to the page everything can work fine the first time, then fail, and then, even without reloading the page, everything works fine.
Here is the code:
$(document).ready(function () {
var lblseguir = $(".lbl-seguir");
var iconSeguir = $('#icon-seguir');
$(".js-toggle-seguir").click(function (e) {
var button = $(e.target);
if (lblseguir.hasClass("label-info"))
{
$.post("/api/seguir", { seguidoId: button.attr("data-user-id") })
.done(function () {
lblseguir
.text("Seguindo")
.removeClass("label-info")
.addClass("label-success");
iconSeguir
.removeClass("fa-user-plus")
.addClass("fa-user");
})
.fail(function () {
alert("Algo deu errado!")
});
}
else
{
$.ajax({
url: "/api/seguir/" + button.attr("data-user-id"),
method: "DELETE"
})
.done(function () {
lblseguir
.text("Seguir")
.removeClass("label-seccess")
.addClass("label-info");
iconSeguir
.removeClass("fa-user")
.addClass("fa-user-plus");
})
.fail(function () {
alert("Algo deu errado!")
})
}
});
}
);