I'm trying to handle the failure function in AJAX to show specific messages to the users. I've tried most the solution and failed 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');
}
});
});
Also, here is my 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 !");
}
When I test my code, it's working well, but it's returns the value always to the success, and in my code, the only value should go to the success is to update the like number else that all the massages should be show in:
<p class="Likes"></p>
How I can control the content I want to return to failure or success?