April 17, 2011

Ajax comments insert LI or replace UL?

Question by Aen Tan

I’m ajaxifying my comments feature and I’m choosing between 2 strategies. My comments list is an unordered list.

  1. Replace UL in DOM with UL from response.
  2. Insert last LI from response into UL in DOM.

The first option is simpler but I feel like it’s not the best or right way.
If I want to use the second option how do I know which comments in the response are newer than the ones in the DOM if more than one comment was posted at the same time?

Thoughts?

Answer by JohnP

You can keep the timestamp as a variable for JS to refer.

When you load the page, your server side language will assign the timestamp of the last comment to be loaded to a javascript variable. From there on, everytime you load more comments, send the last timestamp you requested. Your server side language will check for comments that are newer than that timestamp. Make sure to update the timestamp as you send out more requests. Either by sending it as part of the response or keeping track of when you sent the request.

Answer by Starx

You should append the comment’s UL with latest LIs. Why? you do not have to grab all the full UL list and replace the old one. Reduce the changes that has to be made. Just grab the latest LI and append it at the last. LESS WORK MORE EFFICIENT

So far of your question, about how to know which one is the latest comment. Store timestamp as the comments are stored in the DB. While also fetching the comments for the first time, try to assign the variable holding the timestamp of the last item, then after search the database for everything that is greating the timestamp you stored, get the list and append them, then update the variable, with the latest time stamp again.

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!