0

I have a video based project.In this project I want to implement Likes features. That is there is a hyperlink on each video with the total like count and when user clicks on that hyperlink after then hyperlink is to be hidden and only show Liked text with total count of that video.

I have write this code in JavaScript with Ajax but main problem is that in one session if a user likes 5 videos then 5 times db will be hit. Is there any efficient way to implement it?

<div id="status${video.id}"><a href="javascript:callLike('${video.id}');"> Like-        </a> </div><a id="like1${video.id}" style="color:#ffffff;">${video.likesCount}</a>

function callLike(id)
{

    document.getElementById("like"+id).innerHTML='300';
    var postData = '?Id='+id; 
    var url =protocol+'//'+host+'/xxx/getLike'+postData;     
    // alert("url:"+url);
    if (window.XMLHttpRequest) {
        req = new XMLHttpRequest();
    } else if (window.ActiveXObject) {
        req = new ActiveXObject("Microsoft.XMLHTTP");
    }        
    req.onreadystatechange = likesres;
    req.open("POST", url, true);
    req.send(null); 

}

function likesres()
{
    if (req.readyState == 4) {
        if (req.status == 200) { 
            response = req.responseText;

            document.getElementById("like1"+id).innerHTML=response;
            document.getElementById("status"+id).innerHTML='Liked--';
       }
    }
}
1201ProgramAlarm
  • 32,384
  • 7
  • 42
  • 56
Johnson
  • 33
  • 4
  • Are you sure 5 inserts per session is a problem? :) – Yury Tarabanko Jun 23 '14 at 18:07
  • if that's your main problem, you need to either stop worrying, or get a faster DB... – dandavis Jun 23 '14 at 18:13
  • @dandavis thnks for reply and i think i am using faster Db (MongoDb) but i want to know that if any efficient way better than this becz this project have many users and if they all user individually hit 5 like then at a time db will be hit multipletimes – Johnson Jun 24 '14 at 07:01
  • @YuryTarabanko Thanks yes this is problem if there are many users and i think in linkedin or in facebook they are not using this way. – Johnson Jun 24 '14 at 07:03

1 Answers1

0

You need a better project architecture if you want to make this project scalable.
A starting point of what you should do is implementing an in-memory queue on your server-side code and a processing mechanism for it. Every time a user likes a video, this information is added to the queue and every 2 minutes, the queue is processed and all its content gets written to the database.

This way, you can control how many times the DB will be hit.
However, it might add some delay for the users if you set the processing time too infrequent.

Hope this helps and gives you an idea to what needs to be done.

Mihai
  • 371
  • 3
  • 14