So I have a like button in my index view which looks like this. It calls the function "PostLike" which increases the number of likes by inserting a new row in my "like" table.
<form asp-action="PostLike" asp-route-id="@item.Id">
<input id="btn" type="submit" value="Like" >
</form>
What I want to do is to change the value of the button from like to unlike when it's clicked, without refreshing the page and keeping the value after refreshing the app. Any ideas? I know I have to use some AJAX function for this to work, but I don't know how it should be implemented.
CodePudding user response:
you can make an ajax call to check the success or error request status then change the value on the success method
ArticleLikeObj is the object to be sent to the controller to save like article action and it’s a view model class containing properties like ArticleId and current logged user
ajax call
<input id="@item.ArticleId" onClick="Submit_clicked(this.id)" value="Like" >
<input id="@item.ArticleId" onClick="Submit_clicked(this.id)" value="Like" >
<input id="@item.ArticleId" onClick="Submit_clicked(this.id)" value="Like" >
function Submit_clicked(clicked_id)
{
let ArticleLikeObj = {ArticleId:clicked_id, UserName:"Doe"};
SendRequest(ArticleLikeObj);
}
function SendRequest(ArticleLikeObj) {
$.ajax({
type: "POST",
url: '@Url.Action("action name","controller name")',
data: ArticleLikeObj,
contentType: 'application/x-www-form-urlencoded',
dataType: "json",
success: function (response) {
document.getElementById("Submit").value = "Liked";
},
error: function () {
alert("Error!");
}
});
}