1
I have a button on a tab that calls an API. The button lets you follow a user or stop following.
Clicking on the button changes a label that is next to the button and the symbol that is on the button.
The problem is that sometimes everything works well and sometimes not. I debug and realized that when it fails is because the value goes null to the API. The strange thing is that when you get to the page everything can work well the first time, then fails, and then, even without reloading the page, everything works well again.
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!")
})
}
});
}
);
Can you show HTML? that
.js-toggle-seguir
is the button? I think thee.target
sometimes it’s not the button as expected. Sets the HTML to be clearer.– Sergio
Uuhum. HTML would be great.
– Aline
Open the browser console and then from F5 and start the actions from the beginning until the failure you mentioned occurs, then note if any error occurred in the console, usually things fail in other scripts which causes a "domino effect".
– Guilherme Nascimento