0

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" class="btn btn-primary">
</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.

1 Answer 1

1

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" class="btn btn-primary">

<input id="@item.ArticleId" onClick="Submit_clicked(this.id)" value="Like" class="btn btn-primary">


<input id="@item.ArticleId" onClick="Submit_clicked(this.id)" value="Like" class="btn btn-primary">

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!");
                    }
                });
            }
Sign up to request clarification or add additional context in comments.

4 Comments

Could you explain to me please, what should i put instead of "//data"? What is CreateFromVM exactly? Thats the part i did not understood.
@BiancaTărău I’ve updated the answer and if it is solved "accept" answer
Well the problems is that I have a like button for each article. And the articles are displayed in my view through a foreachloop. So how do i get the specific data, foreach article?
@BiancaTărău I’ve updated the answer also update your question with previous comment and if it is solved "accept" answer

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.