Ahmed Shamel
Ahmed Shamel

Reputation: 1962

Real time insertion of data in mvc

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");

        }
    }

Upvotes: 1

Views: 1985

Answers (5)

Waleed Chayeb
Waleed Chayeb

Reputation: 31

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

Upvotes: 0

Matheus Santos
Matheus Santos

Reputation: 680

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!

Upvotes: 1

Rockster160
Rockster160

Reputation: 1658

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.

Upvotes: 0

Harshul Pandav
Harshul Pandav

Reputation: 1036

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.

Upvotes: 0

Riwen
Riwen

Reputation: 5200

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

Upvotes: 9

Related Questions