Sunday, July 29, 2012

Twitter style Dynamic Tweet update using jQuery and Ajax

We all are well aware of the Twitter platform, every action on Twitter happens dynamically, without page getting refreshed. Even when you post your Tweet, it appears on your Timeline instantaneously without the page refresh. So here today we have code for Twitter like Timeline with Compose tweet functionality, which adds Tweet to the Timeline dynamically using Php, jQuery and Ajax.


Database Design 


  Tweets table :  


CREATE TABLE tweets (
t_id INT PRIMARY KEY AUTO_INCREMENT,
tweet VARCHAR(140),
time INT);


Adding Data to Database

You can yourself add data to the database after creating the above mentioned Table, we advice you to add 4 rows with tid's as (1,2,3,4) and respective tweet and for column Time do enter "126924926" as default. 


  db.php  


In db.php you must change the SERVER_NAME, USERNAME, PASSWORD and DATABASE to your own MySql settings.

<?php
define('DB_SERVER', 'SERVER_NAME');
define('DB_USERNAME', 'USERNAME');
define('DB_PASSWORD', 'PASSWORD');
define('DB_DATABASE', 'DATABASE');
$connection = mysql_connect(DB_SERVER, DB_USERNAME, DB_PASSWORD) or die(mysql_error());
$database = mysql_select_db(DB_DATABASE) or die(mysql_error());
?>





  Index.php  


In index.php you will find the HTML code to design the whole interface along with Php and Javascript to save and POST the tweeted message, using Ajax.

<div id="container">
<div id="sidebar">
<div id="logo"><img src="includes/1.png"></div>
<form action="#" method="POST">
<div><textarea id="tweet" name="tweet" placeholder="Compose new Tweet"></textarea></div>
<input type="submit"  value=" Tweet " class="btn" id="tweet_submit"/> 
</form>
</div>
<div id="main">
<div id="heading">Tweets</div>
<div id="content">
<?php
$sql="select * from tweets order by tid DESC";
$result=mysql_query($sql);
while($row=mysql_fetch_row($result))
{
$time = "$row[2]";
echo "<div class='tweet_box'>";
echo "<div class='tweet_user'><img class='user_img' src='http://www.gravatar.com/avatar/a422402df9e5dc54fab6e8131dd19fd0?s=50'></div>";
echo "<div class='tweet_body'>";
?>
<div class="tweet_time"><?php time_stamp($time);?></div>
<?php
echo "<div><b><a href='http://twitter.com/wtfdiary'>Abhishek Ahlawat</a></b> 
//We have included User as default for this script
<span class='uname'>@wtfdiary</span></div>";
echo "<div class='tweet_text'>$row[1]</div>";
echo "</div></div>";
}
?>
</div>
</div>
</div>




  Javascript  


In the main index page we use javascript to collect data from the Form, and Post it dynamically to post_tweet.php using Ajax.

<script type="text/javascript">
$(function() {
$("#tweet_submit").click(function() 
{
var tweet = $("#tweet").val();
var dataString = 'tweet='+ tweet;
if(tweet=='')
{
alert('Please type your tweet');
}
else
{
$.ajax({
type: "POST",
url: "post_tweet.php",
data: dataString,
cache: false,
success: function(html){
$("#tweet").val('');
$("#content").prepend(html);
}
});
}return false;
}); });
</script>



  post_tweet.php  


This file receives the Posted Tweet from the javascript and Saves it into the MySql table, as well as Show the Tweet on the Timeline. 

<?php
include("includes/db.php");
include_once 'includes/time_stamp.php';
if($_POST)
{
$tweet=$_POST['tweet'];
$time=time();
//Tweet and Timestamp Inserted into Mysql
$query = "INSERT INTO tweets(tweet,time) VALUES ('$tweet','$time')";
$result=mysql_query($query);
//HTML for showing Tweet dynamically
echo "<div class='tweet_box'>";
echo "<div class='tweet_user'><img class='user_img' src='http://www.gravatar.com/avatar/a422402df9e5dc54fab6e8131dd19fd0?s=50'></div>";
echo "<div class='tweet_body'>";
?>
<div class='tweet_time'><?php time_stamp($time);?></div>
<?php
echo "<div><b><a href='http://twitter.com/wtfdiary'>Abhishek Ahlawat</a></b> <span class='uname'>@wtfdiary</span></div>";
echo "<div class='tweet_text'>$tweet</div>";
echo " </div> </div>";
}
else { }
?>


This is the First Level design for our New Twitter Platform Design Script, soon we will Update this script with more features and functionality of Twitter. For any Query, do comment. We will very soon provide you with Demo of all our Scripts



16 comments:

  1. Nice tutorial..
    Are you going to finish this?

    ReplyDelete
  2. yes, we will shortly update this tutorial to include more functions. Stay Tuned !

    ReplyDelete
  3. What is this 1998? This is awful.

    ReplyDelete
  4. This is susceptible to SQL injection attacks - DO NOT USE THIS!!

    You are still using mysql_, which is being deprecated. You should be using PDO or mysqli_.

    Don't write tutorials if you don't know what you are doing - it just proliferates the bad programming out there.

    ReplyDelete
    Replies
    1. Hello Nick,
      We do know that mysql_ is a deprecated function. I think everybody knows it. But here in our tutorials we just aim to give a basic level script to users so that they understand the structure and functioning easily.

      We have never claimed that these scripts are bug free or highly secure. You can change them as per your requirements.

      We provide you with the raw component.

      I appreciate your concern. Thanks for your comment. Next time we come up with any script, we will surely use mysqli_ function.

      Delete
    2. Sorry, but that is a crap response. If most of your users are looking for basic instructions, it means that they are new to this type of programming. If they are new to this type of programming, it means that you have an even greater responsibility to make sure you do not provide them with incorrect information or start them out with bad programming habits.

      Delete
    3. Ok, its your opinion, and i consider it valid. From next time, you will be seeing mysqli_ in my scripts.

      Delete
    4. Nick, I am a beginner in php/mysql. For a beginner, this web is the ideal. If you are so pro why are you reading a tutorial? The tutorials are introductions. I think that when you saw "twitter style dynamic..." you thought that Abthisthek was going to give you the code of twitter!
      Man, think about it

      Delete
    5. Thank you Federico for appreciating our work.

      Delete
  5. Great post man! How can I make to refresh dynamically the tweets every 20 seconds? thanks

    ReplyDelete
    Replies
    1. We are working on to upgrade this script, adding more functions, soon the new script will be available, we will surely try to include this function to it. Keep Visiting.

      Delete
  6. Hi,

    if I understand correct, the list is only updated when I post something new. Is there are way to automatically check the database for new entries every 10 seconds if maybe someone else made any update to it?

    ReplyDelete
  7. Hi @Ahlawat, it's been a year now, where are still waiting for the script o.

    ReplyDelete