• Home
  • Twitter and weibo example by PHP JQuery and AJAX

Twitter and weibo example by PHP JQuery and AJAX

December 29, 2011 Ning 7 Comments

View demo click here
Download demo

Creating the DB

If you’d like to run a working demo on your own site, you will have to create a MySQL table where all your tweets are going to be stored. You can run the following SQL code through phpMyAdmin (the code is also available in table.sql in the tutorial files):

CREATE TABLE `demo_twitter_timeline` (
  `id` int(10) NOT NULL auto_increment,
  `tweet` varchar(140) collate utf8_unicode_ci NOT NULL default '',
  `dt` datetime NOT NULL default '0000-00-00 00:00:00',
  PRIMARY KEY  (`id`)

The table can be in any mysql database. Just remember to update the data in connect.php

remove tweets older than 1 hour to prevent spam
SUBTIME() returns expr1 – expr2 expressed as a value in the same format as expr1. expr1 is a time or datetime expression, and expr2 is a time expression.

mysql_query("DELETE FROM demo_twitter_timeline WHERE id>1 AND dt

Fetch the timeline
$q = mysql_query("SELECT * FROM demo_twitter_timeline ORDER BY ID DESC");

replace http:// to link


.bind( eventType [, eventData], handler(eventObject) )
eventTypeA string containing one or more DOM event types, such as "click" or "submit," or custom event names. eventDataA map of data that will be passed to the event handler.handler(eventObject)A function to execute each time the event is triggered

The .attr() method gets the attribute value for only the first element in the matched set. To get the value for each element individually, use a looping construct such as jQuery's .each() or .map() method.

.submit() This method is a shortcut for .bind('submit', handler) in the first variation,

	$('#inputField').bind("blur focus keydown keypress keyup", function(){recount();});

In an HTML document, .html() can be used to get the contents of any element. If the selector expression matches more than one element, only the first match will have its HTML content returned. Consider this code:

function recount()
	var maxlen=140;
	var current = maxlen-$('#inputField').val().length;
	if(current<0 || current==maxlen)

	else if(current<20)


We can divide this code into three important paths. The one that gets executed after the page is loaded. The recount() function, that fills our counter span with the number of characters left, and the tweet() function that handles the AJAX communication and the subsequent page update to include the new tweet in the timeline.

In the first part, you see that we bind the recount() function to a number of events that may happen in the text area. This is because any one of those events by its own cannot guarantee fast enough updates on the counter.

On the next line we disable the submit button – we do not need the user to be able to submit an empty form.

Later we bind the onsubmit event of the form to the tweet() function, preventing the actual form submit on line 9.

In the recount function there are a number of things that are worth mentioning. we calculate the remaining characters, depending on how close we are to the maximum number, set the color of the counter.

We also decide whether we should disable the button (if there is no text in the text area, or we are over the limit) and enabling it otherwise. The disabling / enabling of the button happens by setting the attribute disabled and assigning our custom CSS class – inact, which removes the hand cursor and changes its color to light grey.

function tweet()
	var submitData = $('#tweetForm').serialize();
		type: "POST",
		url: "submit.php",
		data: submitData,
		dataType: "html",
		success: function(msg){
				$('ul.statuses li:first-child').before(msg);


.before( function )
functionA function that returns an HTML string, DOM element(s), or jQuery object to insert before each element in the set of matched elements. Receives the index position of the element in the set as an argument. Within the function, this refers to the current element in the set.

.append( content [, content] )
contentDOM element, HTML string, or jQuery object to insert at the end of each element in the set of matched elements.
contentOne or more additional DOM elements, arrays of elements, HTML strings, or jQuery objects to insert at the end of each element in the set of matched elements.

stripslashes — Un-quotes a quoted string
strip_tags — Strip HTML and PHP tags from a string
mysql_real_escape_string — Escapes special characters in a string for use in an SQL statement
mb_strlen — Get string length


$_POST['inputField'] = mysql_real_escape_string(strip_tags($_POST['inputField']),$link);

if(mb_strlen($_POST['inputField']) < 1 || mb_strlen($_POST['inputField'])>140)

mysql_query("INSERT INTO demo_twitter_timeline SET tweet='".$_POST['inputField']."',dt=NOW()");


echo formatTweet($_POST['inputField'],time());


    May 21, 2014 REPLY

    Superb, what a website it is! This web site provides valuable facts to
    us, keep it up.

    June 10, 2014 REPLY

    Magnificent beat ! I wish to apprentice whijle you amend youhr website, howw could
    i subscribe for a blog web site? Thhe account aided me a
    acceptable deal. I had been a little biit acquainted of this your broadcast provided bright
    clear concept

    June 11, 2014 REPLY

    My partner and I stumbled over here different web page and thought I
    may as well check things out. I like what I see so now i am following you.
    Look forward to looking at your web page repeatedly.

    June 15, 2014 REPLY

    Hi there! I know this is somewhat off topic but I was wondering which blog
    platform are you using for this site? I’m getting fed up of WordPress because I’ve had problems with hackers and I’m looking at options for another platform.

    I would be fantastic if you could point me in the direction of a good platform.

    August 22, 2014 REPLY

    I enjoy what you guys are up too. This type of clever work
    and coverage! Keep up the good works guys I’ve you guys
    to our blogroll.

    September 2, 2014 REPLY

    I read a lot of interesting posts here. Probably you spend a lot of time writing, i know how to save
    you a lot of work, there is an online tool that creates high quality,
    google friendly posts in seconds, just type in google – laranitas free content

    November 30, 2015 REPLY

    Even so, in this case, my positions have been left open and they began to trigger the
    auto -liquidation 40 mins later after the SNB announcement.

leave a comment