Skip to content Skip to sidebar Skip to footer

How To Make A Feed From User Submitted Posts

I'm trying to figure out how to use AJAX to create a Twitter-like feed that displays user's posts on the same page immediately after they push the submit button. It would be an inf

Solution 1:

All you need is a server-side script with an SQL query that would return newer posts. have your javascript store a variable of the date or of the last post id (used PHP for clarification):

result = mysql_query("SELECT ID,POST FROM POSTS WHERE DATE>" . $_GET['date']); //oruse WHERE ID> $_GET['id']
while(rows[] = mysq_fetch_array(query));
print json_encode(rows);

now you have a server-side script that will return new posts, so all you have to do is write javascript function for the more button:

updatePosts = function () {
   $.ajax({
           url: 'serversiderUrl?lastId=' + last_id, //last_id is global variable for the id of the last post on the pagesuccess: function(data){
                        data = JSON.parse(data);
                        for(i in data){
                            $('#posts_container').append(data[i].post); //do your appending functions here
                            last_id = data[i].id;
                         }
                     }
}

now for posting new entries create a server-side script of your favorite language that handles new posts:

result = mysql_query("INSERT INTO POSTS VALUES(''," . urldecode($_POST['POST']) . ")");

now for the client side:

submit_post = function(){
   $.ajax({
           type: 'POST',
           url:'yourposturl',
           data: "post=" + encodeURIComponent($('#textArea').text()),
           success: function(){
                          updatePosts(); // call the function that update the posts so the new entry is now added to the page
                }
   });
}

Now bind the functions to the appropriate buttons when the document is fully loaded:

$(document).ready(function (){
    $('#moreButtonId').click(updatePosts);
    $('#submitButtonId').click(submitPost);
});

Solution 2:

There are many ways such as the submit button kept sending it to the database while we'd append text to a container underneath. Or we can update the container underneath to create a container (page) that are similar, after the ajax response is successful then we append the data to the container beneath

$.post(url,function(data){
    //Here you can append the data responsed by the ajax request to the container underneath
});

But you have to have a exactly same view with a conatiner (feed container) existing in the currently page

Post a Comment for "How To Make A Feed From User Submitted Posts"