1

I have a news project with comment feature. Any one who add a comment can see his comment immediately without reloading the page ( using ajax ). The problem is that when user1 ( for example ) comment on post1 , only user1 can see his comment immediately but all other users need to reload the page to see the comment of user1. How can I solve this problem ?

The code I am using to get the comment :

$(function () {
  $("#AddComment").click(function () {

  var CommentText = document.getElementById("CommetForm").innerHTML;
    var UserName = document.getElementById("UserName").innerHTML;
    var PostId = document.getElementById("PostId").innerHTML;


       $.ajax({
                url: '/PostComment/AddComment',
                type: 'POST',
                dataType: 'json',
                cache: false,
                data: { "PostId": PostId, "CommentText": OrignalCommentText },
                success: function (data)
                {
                    if (data == "P") // Commet Stored on database successfully
                    {
                    document.getElementById("PostComments-" + PostId).innerHTML += 
                    "<li>" +
                                    "<div class='media'>" +
                                        "<div class='media-body'>" +
                                            "<a href='' class='comment-author'>"+UserName+"</a>" +
                                            "<span class='CommetText' id='CommentText-" + PostId + "'>" + CommentText + "</span>" +
                                        "</div>" +
                                    "</div>" +
                                "</li>";

                    }

                    else // Some Error occur during storing database
                    {

                        document.getElementById("CommentError-" + PostId).innerHTML = "\nSomething went wrog, please try agin";

                    }



                }
            });
});
});

And This code for storing comment in database :

  private SocialMediaDatabaseContext db = new SocialMediaDatabaseContext();

  [HttpPost]
    public JsonResult AddComment(string PostId, string CommentText)
    {
        try
        {
            Users CurrentUser = (Users)Session["CurrentUser"];
            PostComment postcomment = new PostComment();


            CommentText = System.Uri.UnescapeDataString(CommentText);


            postcomment.PostId = int.Parse(PostId);
            postcomment.CommentFromId = CurrentUser.UserId;
            postcomment.CommentText = CommentText;
            postcomment.CommentDate = DateTime.Now;

            db.PostComments.Add(postcomment);
            db.SaveChanges();
            return Json("P");

        }

        catch
        {
            return Json("F");

        }
    }
Erik Funkenbusch
  • 92,674
  • 28
  • 195
  • 291
Ahmed Shamel
  • 1,982
  • 3
  • 24
  • 58

5 Answers5

9

I suggest you use SignalR for this. http://www.asp.net/signalr/overview/getting-started/introduction-to-signalr

Riwen
  • 4,734
  • 2
  • 19
  • 31
1

TL;DR Use can use setInterval or Websockets to accomplish this. Below I explain how.

First of all, we need to understand what is behind this Publish/Subscribe pattern. Since you want to build a real-time application, you may create a function that asks to your server if some data was added since last time it was checked.

USING WindowTimers.setInterval()

Here is the simplest way to accomplish this in my point of view, assuming that's your first time and you never worked with websockets before. For instance, in your client-side project you create a function within a setInterval setInterval( checkNewData, time). Your method checkNewData() will make an ajax requisition to your server, asking if some data was added recently:

function checkNewData() {
    // ajax call   
    // On response, if found some new comment, you will inject it in the DOM
}

Then, in your server-side method, get the timestamp of its call and verify in your database if there are some data. Something like this:

// Method written in PHP
public function ajax_checkNewData() {
    $time = time();

    // Asks to your model controller if has something new for us.
    // SELECT comment FROM comments WHERE timestamp > $time
    // Then return its response
}

You will use the response that came from your controller method ajax_checkNewData() to write on your comments-container.

USING WEBSOCKETS (beautiful way)

Now, there are another way to do this, using WebSockets. HTML5 WebSocket represents the first major upgrade in the history of web communications. Before WebSocket, all communication between web clients and servers relied only on HTTP. Now, dynamic data can flow freely over WebSocket connections that are persistent (always on), full duplex (simultaneously bi-directional) and blazingly fast. Amongst different libraries and frameworks, you can use socket.io. I believe this will solve your real-time application problem pretty good, but I am not sure how much of your project you will need to change to suit this solution.

Check it out the simple chat tutorial from SocketIo page and see for yourself if it fits to your needs. Its pretty neat and would be a good challenge to implement using it. Since its event-driven, I believe you wont have problems implementing it.

For further information check it out:

REFERENCES

Get Started: Chat application - http://socket.io/get-started/chat/

Websockets - http://en.wikipedia.org/wiki/WebSocket

WebSockets - https://developer.mozilla.org/en/docs/WebSockets

Good luck!

Matheus Santos
  • 680
  • 8
  • 16
  • Thanks for your replay, but I think signalr is good solution, but for more information about real time, is signalr is best or WebSocket ? – Ahmed Shamel Dec 06 '14 at 18:42
  • 1
    SignalR uses the WebSocket transport to perform its magic. So, since you are using ASP.NET in your project, SignalR suits best to your real-time application. If you are curious about it, you may check this [article](http://sim4all.com/blogging/?p=454) or [@Damian Edwards's answer on this question](http://stackoverflow.com/questions/9537641/node-js-socket-io-vs-signalr-vs-c-sharp-websocket-server) – Matheus Santos Dec 06 '14 at 19:01
0

You could write a JavaScript code which makes ajax call to a servlet that checks for updates in the database. Return a flag to the success function of the ajax call and If the state has changed or any comment added to the database, you can reload the page or refresh the consisting of the comments with the new comments.

Harshul Pandav
  • 1,016
  • 11
  • 23
0

It's not posting on other pages, because the user1 page is making an AJAX call, so it loads correctly. However, the other pages don't 'know' they are supposed to reload via AJAX. You need some kind of timed loop running that checks for any changes. Either of the above answers should work for it.

Rockster160
  • 1,579
  • 1
  • 15
  • 30
  • Thanks for your answer, but timed loop or any kind of polling will exhaust the server if there are a lot of users who comment on the same post – Ahmed Shamel Dec 06 '14 at 18:48
0

You could use SignalR for this, you can send realtime messages to the server, here is a sample to know how to implement SignalR in ASP.NET MVC

https://github.com/WaleedChayeb/SignalRChatApp