i'm doing a project that have a social network like facebook, i need to update likes count without refresh (ajax) using jsrender, thats my code:
how can i replace the number of the likes that post have with ajax?
<script type="text/x-jsrender" id="postsTemplate">
...
<div class="feed-post-options">
<div class="feed-post-buttons" data-postId="{{:PostId}}">
<p class="post-feed-options" id = "postLikesCount">{{:PostLikesCount}}</p>
{{if PostIsLiked }}
<a class="small-icons-feed" href="javascript:likePost('{{:PostId}}')"><span class="glyphicon glyphicon-thumbs-up like"></span></a>
{{else}}
<div>
<a class="small-icons-feed" href="javascript:likePost('{{:PostId}}')"><span class="glyphicon glyphicon-thumbs-up-checked like"></span></a>
</div>
{{/if}}
<p class="post-feed-options">{{:NumberOfComments}}</p>
<a class="small-icons-feed" href="#"><span class="glyphicon glyphicon-comment comment" title="Comment"></span></a>
<p class="post-feed-options">0</p>
<input id="postIdValue" type="hidden" value={{:PostId}} />
<a class="small-icons-feed" href="javascript:shareModal('{{:PostId}}')" name="Save" data-toggle="modal" data-target="#shareModal" onclick="shareModal('{{:PostId}}')"><span class="glyphicon glyphicon-share share" title="Share"></span>
</a>
</div>
...
</div>
....
</script>
<script type="text/javascript">
function likePost(postId) {
var appUserId = $("#appUserValue").val();
var request =
$.ajax("/Home/LikeComment", {
type: "GET",
dataType: "html",
data: { appUserId: $("#appUserValue").val(), postId: postId },
success: function (data) {
//how can i replace the number of the likes without refresh
}});
request.done(function(jqXHR, textStatus){//just debug
alert("Request done: " + textStatus)
});
request.fail(function(jqXHR, textStatus) {
alert( "Request failed: " + textStatus );
});
}
</script>
</div>
You can use jQuery to modify the text content of the element:
<p class="post-feed-options" id="postLikesCount">{{:PostLikesCount}}</p>
and set the innerText to the new updated count.
Alternatively you can use JsViews to bind to the data (see http://www.jsviews.com/#jsv-quickstart), and then update the PostLikesCount
observably - which will automatically trigger an incremental update of the innerText:
<p class="post-feed-options" id="postLikesCount">{^{:PostLikesCount}}</p>
or
<p class="post-feed-options" id="postLikesCount" data-link="PostLikesCount"></p>