I've been trying to manage the failure function in AJAX to display specific messages to users. Despite attempting various solutions, I have struggled to control the failure function. Here is my code:
<p id="Likes" class="alert-danger" style="display:none"></p>
<button title="Like" id="Like" data-id="@Model.Book.Book_id" class="like-toggle btn btn-group-sm red fa fa-2x" style="float:initial">❤ @Model.Book.Likes_Count</button>
$('.like-toggle').click(function () {
var myId = $(this).data('id');
$.ajax({
type: "GET",
url: '@Url.Action("Like", "Book")?Book_id=' + myId,
success: function (response) {
document.getElementById("Like").innerHTML = response;
},
failure: function (response) {
$('#Likes').html(response).fadeIn('slow');
$('#Likes').delay(8000).fadeOut('slow');
}
});
});
Additionally, here is the controller code:
[HttpGet]
public ActionResult Like(int? Book_id)
{
int state = 0;
if (User.Identity.IsAuthenticated)
{
var x = User.Identity.GetUserId();
var CheckIfExist = db.Likes.Where(p => p.Book_Id == Book_id && p.User_Id == x.ToString()).FirstOrDefault();
if (CheckIfExist != null)
{
return Content("You Liked This Book Before !");
}
else
{
if (x != null)
{
var article = db.Books.Find(Book_id);
if (article != null)
{
article.Likes_Count += 1;
state = db.SaveChanges();
if (state == 1)
{
Like likes = new Like
{
Book_Id = article.Book_id,
User_Id = x
};
db.Likes.Add(likes);
state = db.SaveChanges();
if (state == 1)
{
return Content("💗 " + article.Likes_Count.ToString());
}
else
{
return Content("Failed To Save Your Like To DataBase !");
}
}
else
{
return Content("Failed To Save Your Like To DataBase !");
}
}
else
{
return Content("Book Does Not Exists In DataBase !");
}
}
}
}
return Content("Only Registered Members Can Use Our Like System , Please Register To Be Able To Use Our Like System !");
}
While my code appears to be functioning correctly during testing, it consistently returns values to the success function only. According to my code, any message besides updating the like count should be displayed in:
<p class="Likes"></p>
How can I determine which content should be returned to either the failure or success?