Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create stackoverflow's post voting like jquery/ajax function?

Can I use Jquery to call an action and then change the image when it success, just like stackoverflow's post voting function?

In my view, I'm using the following code, but I don't want to refresh the browser. Can anyone provide some code about this for me?

Many thanks.

<%if (!item.IsPrinted)
{ %>
     <%=Html.ImageLink("~/Content/images/web/delete.png", "printed", "MarkAsPrinted", "Order", item.TaskID, null, null)%>
 <%}
 else
  {%>
       <img src="~/Content/images/web/star.png" alt="printed" />                    
  <% }  %>
like image 390
Daoming Yang Avatar asked Aug 14 '26 18:08

Daoming Yang


1 Answers

Generally you should call helper methods through ajax call for this purpose rather than calling your action through ajax. Then, in the helper method, update the value of the score (like storing the latest value to the databse etc) and in the success method of ajax display the appropriate image

Edit:

public string UpdateVoteScore(int postId, int value) {
     // store value to database

     return "success";
}

In JavaScript:

var UpdateScore = function(postId, newValue) {
   $.ajax({
           type: "POST",
           url: /YourController/UpdateVoteScore,
           data: { postId: postId, value: newValue },
           success: function(result) {
              // replace your image
              $("#MyImage" + postId).attr("src", "some new image path here");
           },
           error: function(req, status, error) {
           }
    });
}

In View:

<img id='<%= "MyImage" + post.Id %>' 
     src="some image path"
     onclick="UpdateScore(scoreValueHere);"></img>

Note: post will be changing as you do this in a loop, so the post.Id will be unique and thus makes the image id unique

like image 187
Mahesh Velaga Avatar answered Aug 16 '26 07:08

Mahesh Velaga