Tuesday, July 28, 2009

How to solve Internet Explorer cache issue in Ajax


This is a frequent asked question which can be solved simply with a line of code with javascript.

The problem
If you use Internet Explorer you can find an annoying problem when you send multiple requests using Ajax. All new requests after the first request (using http.open method), mantain the same value of the first request. This problem is caused by Internet Explorer use of cache.

Solution

When you call the method:

http.open


add a random variable using Math object and add it in the method's URL argument, for example:

nocache = Math.random();
http.open('get', 'page.php?url_parameter='+parameter+'&nocache = '+nocache);


In this way all the new request will have an URL parameter (&nocache) which force the browser to "refresh" the old value with the new value.

Bookmark and Share
Digg this

How to design a sexy header for your site using CSS


Step by step tutorial to implement a typographic style header using Photoshop and CSS.

Yesterday I received a lot of positive messages about the new template of my site. Expecially for the new header (in particular the green bar on top of the page). Some of my readers asked to me to dedicate a post about how to realize a similar "graphic composition", so I decided to publish a post with the "process" I use in general to design graphical sections for my web sites.

First approach: be simple.
The most important rule is: be simple. Avoid complex CSS structure beacuse in most cases it is not necessary. Woork header is composed from three DIV elements:

- Logo layer
- Navigation bar
- Green site introduction section

Each element has a fixed width but how navigation bar and site introduction section fit the page size. So you need other two liquid layer (width=100%) which will contain your navigation bar and introduction section. You can schematize this layout in this way:



Another solution to avoid container layers is applying a background picture to the <body> section using css, but I prefer working with pure layer instead of images to have more control on the design. In fact if you use a background image for the body, if you decide to change for example height or color of the navigation bar you have every time also changing the background image.


Design the header with Photoshop
A good practice is trying to design first your header in Photoshop to have an idea about how it will look. Replicate with Photoshop the header structure and choose some colors for its elements until you are not satisfied for the result:


When you think your header is ok you can start to convert the picture into HTML and CSS code. Before you leave Photoshop, create an image to apply to site introduction section background. This is a small image like this:

HTML and CSS code
HTML code for your header is very simple:

<div id="logo"></div>
<div id="navbar-container">
<div id="navbar">
<a href="#">Home</a>
<a href="#">About</a>
<!-- Other links here...-->
</div>
</div>

<div id="int-site-container">
<div id="int-site">
</div>
</div>

... and CSS code is:

/* Reset Body Property */
body{border:0; margin:0; padding:0;}
#navbar-container{background:#000000;}
#int-site-container{
background:url(img/int-bg.png) left top repeat-x;
height:166px;
}
#logo, #navbar, #int-site{
width:800px;
margin:0 auto;
}
/*------------------*/
/* LOGO */
#logo{height:54px;}

/*------------------*/
/* Nav Bar */
#navbar{
height:26px;
line-height:26px;
}
#navbar a:link, #navbar a:visited, #navbar a:hover{
color:#FFFFFF;
font-weight:bold;
margin-right:20px;
text-decoration:none;
}

Create Rays of Light for introduction section background
To improve the look of my header I choose to add a background with a simple graphical element: some rays of light. To create this effect, create a triangle using Photoshop Pen Tool. Copy this object and rotate the new object of 20 degrees (set the rotation point to left-bottom):


Repeat this action until you designed a semi-circle. Select all element and create a smart object (selecting all "ray of light" layers and clicking on right mouse button -> create smart object). Then create a selection on the orange background and paste into the selection the smart object with your "rays of light". Set the Fill percentage to 19% and apply Color Burn filter to "rays of light" layer. The result is like this:


...and now free your creativity adding graphical element to your site introduction section. On my site I chose a simple typographic style adding a tag cloud of the main topics which my readers can find on woork.


If you are looking for nice fonts to download for free, I suggest to try on dafont.com, a great resource to find inspiration and all fonts you need.
Now, last step, add the image background you created into your CSS code:

#int-site{background:url(img/site-intro.png) left top no-repeat; height:166px;}

It's all!

Download to see the result

I hope this post can help you to find inspiration from "simplicity" to design your site.

Bookmark and Share
Digg this

One shot, one kill: how to become popular with (almost) each post you write on your blog


Do you need traffic for your website? Take a look at these simple tips...

This post is dedicated to every people who wrote me asking to me how I made popular a lot of my posts on delicious in the past weeks. There is a "simple" way to make popular your post and assure a costant high traffic on your site for a medium period conquering a place on delicious home page... and this is what you have to do.




Step 1: Write something interesting
...otherwise it's all useless.

Step 2: your link on delicious/popular page
If you want to conquer delicious home page with your new post, the first step is do appear your new post/link on del.icio.us/popular page:




How can you do it? It's not so difficult if you have a medium daily traffic and a god number of feeds subscribers. I noticed in average 10-12 votes on delicious (users who save your link to their bookmars) in 30 minutes are enough to do appear your link on delicious/popular page and - this is the good news - immediatly you'll receive a high number of new visits from this page.

The "bad" news is: if you want to remain for a long time on delicious/popular page page (and in this way have a possibility to conquer delicious home page) you have to mantain an increasing votes trend for your link. And how can you do it? The faster way is using social network to promote your new post.


Step 3: Publish it and promote it on social networks
In general I use this simple... let me say... "rule" which works very well: when I publish a post on Woork the first thing I do is add it to some general news sites (I use only digg, mixx, reddit) and other niche websites related to the topics about which I write on my blog (Dzone, Design Float and CSS Globe).




Combined effect in terms of visits from these websites produces in general the hoped result and the number of people who save your link on delicious will increase quickly. In this way after one / two hours your link on delicious will catch up 100 votes, enough to appears on delicious home page!

Bookmark and Share
Digg this

How to create an awesome eBook Template using Word or Apple Pages


Today I received some requests about The Woork Handbook template I published yesterday. Some readers asked to me to distribute that template for their eBooks. So in this post I want to illustrate some guidelines to create an awesome eBook template, quickly and in few steps.

I prepared the template which you can download (for Apple Pages and Microsoft Word) and reuse it for your eBooks (I used Apple pages to write the eBook!).

Download Apple Pages template Download Microsoft Word template


eBook Format
You can print the eBook on A4 format page (2 pages for each facade). This is the screenshot:




Document structure
The document is divided in sections. Each section is a chapter. Use "section break" to separate each chapter in this way:



Adding a section break:

- Apple Pages: Insert > Section Break
- Microsoft Word: Insert > Break > Section break (next page)


Page header
This is a not necessary element but i like have a short description in the header of the my pages. It's a simple text on top of your page with above a line which separete the header from the rest of the page:




In general "page header" isn't placed on the first page of the chapter:

- Apple Pages: select layout button on the inspector and flag the option: First Page is different.



- Microsoft Word: double click on the page header and select different first page from the header/footer toolbar.


Chapter structure using document styles
When you work with a text document (using Word, Apple Pages, OpenOffice...), a very good practice is to define your custom styles for the elements of your pages. In this way, every time you decide to modify the look of an element (for example "chapter title"), it will be update automatically in all elements of your document which use that style. For example take a look at the following picture which represents a generic chapter structure:



We have the following elements with related styles:

Chapter title -> Heading 1
Article title -> Heading 2
Paragraph header -> Sub header paragraph
Normal text -> Body
Code box -> Code
Footnotes -> Notes
Article footer -> Small header + small body

You can define your custom style in this way:

- Apple Pages: View > Show Style Draver and then selecting a style and modifying style properties, or creating a new style.
- Microsoft Word: Format > Style and then selecting a style and modifying style properties, or creating a new style.

Note: I used Qlassik font for the title of chapters and articles. You can download it here. In this version of template I used Arial in case you don't have Qlassik font.


Table of contents
Adding a TOC it's very simple:

- Apple Pages: Insert > Table of content.
- Microsoft Word: Insert > Document element > Table of content

Your TOC will be updated automatically every time you add a new content in your document but (this is really important!) you have to use style elements created for the chapter title and article title (Heading 1 and Heading 2).

It's all! I hope this template can help you to prepare quickly your eBook.

Every suggestion is appreciated :)

Note: I used Apple Pages to create my eBook, and I simply converted Pages template for Word. I experienced there are some litte problems with formatting which you convert a document in Word from Apple Pages... tell me if you have them!

Bookmark and Share
Digg this

How to skin HTML form elements in seconds


In the past weeks I received some requests from my readers which asked to me to suggest a simple way to skin HTML form elements. There are a lot of ways to do that and a lot of posts with interesting resources about this topic. But if you want to save time and obtain a nice result I suggest you to use jqTransform or NiceForms.

Both scripts are very useful and simple to use. If you want to use a "native" script which doesn't use an external JS framework (such as jQuery or MooTools) I think a good choice is NiceForms otwerwise, if you use jQuery, a good alternative is jqTransform. Take a look how they work.

1. jqTransform
jqTransform is a jQuery styling plugin wich allows you to skin quickly form elements in a very easy way. The only thing you have to do is to add a javascript inclusion to this plugin in the header section of your web page, create your form and add two lines of JS code to apply the transformation to your form.

Use this code to add a javascript inclusion to jqTransform:

<script type="text/javascript" src="jquery.jqtransform.min.js">
</script>

...now create a form with class property equal to jqTransform:

<form class="jqTransform">
<!-- Add form elements here... -->
<form>

...then add this JS code to apply the transformation:

<script type="text/javascript">
$(function() {
$("form.jqtransform").jqTransform();
});
</script>


2. NiceForms
Niceforms is a script that will replace the most commonly used form elements with custom designed ones. You can either use the default theme that is provided or you can even develop your own look with minimal effort.

To implement form style transformation you have to add a javascript inclusion to NiceForms in your web page using this code:

<script type="text/javascript" src="niceforms.js">
</script>

...then create a form with class property equal to niceform:

<form class="niceform">
<!-- Add form elements here... -->
<form>

It's all. Really simple and fast!

Any suggestion? Please leave a comment.

Bookmark and Share
Digg this

How to implement a Post-to-Wall Facebook-like using PHP and jQuery


In the past months I received a lot of request to write a tutorial for beginners in order to explain how to implement a Post-to-Wall Facebook-like. So, I prepared this very simple example which helps everyone understand how to implement this feature in a website using just some lines of PHP and JavaScript code.

Take a mind, every post in the Facebook Wall contains a lot of information (user, sender, message content, date, number of comments, ...):



But how I said, this tutorial is for Ajax/jQuery/PHP beginners. So I decided to simplify the original Wall using just a single information: the message content.





In this tutorial we have these files:
- confing.php (database connection parameters)
- index.php
- insert.php
- jquery.js
How the Wall works?



index.php contains a form with id "submit_form" with an input text with id "message_wall". When an user submits a new message. Then the new message is appends to top of the ul list with id "wall" with a nice fade-in effect (with jQuery). Ok, now take a look at the code.


1. index.php
index.php is very simple and contains just simple HTML code:

<form id="submit_wall"&gt;
<label for="message_wall">Share your message on the Wall</label>
<input type="text" id="message_wall" />
<button type="submit">Post to wall</button>
</form>

<ul id="wall">
</ul>

The <ul> list with id "wall" is the "container" of messages which are posted into the wall.


2. JavaScript Code
Open index.php and include jQuery in the <head> tag of the page:

<script type="text/javascript" src="jquery/jquery.js"> </script>

...then add this simple function to enable Ajax functionalities to insert the message posted from the user into a database table without reload the page:

<script type="text/javascript">
$(document).ready(function(){
$("form#submit_wall").submit(function() {

var message_wall = $('#message_wall').attr('value');

$.ajax({
type: "POST",
url: "insert.php",
data:"message_wall="+ message_wall,
success: function(){
$("ul#wall").prepend("<li style="display: none;">"+message_wall+"</li>");
$("ul#wall li:first").fadeIn();
}
});
return false;
});
});
</script>

.prepend(...) is a jQuery function to insert elements inside, at the beginning, of a specific element (in this case UL list with id wall -->$("ul#wall")). When the new message is added into the list is hidden (display:none). Then it appears with a fade-in effect:

$("ul#wall li:first").fadeIn();

ul#wall:first: gets the first li element (the last added) into the ul list with id "#wall".


3. insert.php
insert.php contains some lines of PHP code to insert the new message into a database table. In this example I created a table WALL with just one attribute "message". PHP code is very simple:

<?php
if(isset($_POST['message_wall'])){
/* Connection to Database */
include('config.php');
/* Remove HTML tag to prevent query injection */
$message = strip_tags($_POST['message_wall']);

$sql = 'INSERT INTO WALL (message) VALUES( "'.$message.'")';
mysql_query($sql);
echo $message;
} else { echo '0'; }
?>


That's all! Download the source code ready to use in your web projects.




Add a comment for questions or suggestions, thanks!

Bookmark and Share
Digg this

How to manage a small web project: a simple approach


Some times ago I wrote a post about a structured process you must know to develop a web application and many readers asked to me to write something simpler about how to manage a small web project. I think there are not general rules for that but, without doubt, a correct approach can help you manage your projects more efficently and achieve quickly the final result.

I prepared this picture that illustrates a simple process with 3 main phases you can use as reference to manage a small web project:



1. Planning

Plan what you have to do, how you have to do it and in which time.

1.1 Define project scope

First step: Identify 4-5 high-level points which define the scope of your project. Don't underrate the importance of this step because if you are able to describe your project in a nutshell, it means you have a clear idea about what you have to do. So it will be simpler to realize it.

1.2. Identify main features to implement

Second step: Identify main features of your web project and add, for each of them, some details such as relationships, general notes, ecc. For example image to have a simple project with only two main features: user login and profile management. You can represent them in this way:



That's a simplified example only to give you an idea.


1.3. Define sitemap

Next step: define a sitemap of your project with files and folder. Be accurate in identifying all files to implement (HTML/PHP page, JavaScript files,...) because they are final deliverables to implement.




1.4. Plan a daily to-do list

Set daily milestones using a simple to-do list. So everyday you'll know exactly what you have to do. In this way, you can easy monitor your progress measuring what you did a certain day and what had to do.




2. Developing and testing

In this phase: write HTML, CSS, PHP, JavaScript... code and test small portions of code during developing (preliminary test). So it wil be simpler find bugs and errors. When your web application is ready, stress it with a final test to catch errors you didn't find during preliminary test which cause unexpected behaviors .


3. Publishing

Now you are ready to publish your project on-line. When your website or web application is on-line do a last test on what you published to assure you that it's all ok. That's all!

If you have some suggestion please leave a comment, thanks!


External links
Take also a look at these links:

- Software development methodology
- Agile software development - Wikipedia, the free encyclopedia
- Manifesto for Agile Software Development


Related posts
- Structured process you must know to develop a web application
- Simple process to estimate times and costs in a web project

Bookmark and Share
Digg this

How to implement a news ticker with jQuery and ten lines of code


After my previous posts about how to implement a news ticker with MooTools I received a lot of emails from my readers that asked to me to implement a similar feature with jQuery, including fade in and fade out effects, in the simpler possible way. So in this post I want to illustrate you how to implement a nice news ticker using jQuery and just ten lines of Javascript code. The result is something like this:




I suggest you to take a look at this live preview and download the source code to understand how it works. In the source code I added a file called base.html that contains the basic structure of this ticker you can quickly reuse and customize in your web project.





A little introduction
Step 1: image to have a <ul> list with ID = listticker. This list contains some list elements <li> (in this case: My News 1, My News 2, ...). First step is: get the first element of the list, save its content into a var and remove it using a fade out effect.



You can get the HTML code contained into the first element of the list (#listticker) and assign it to a var (first) using this simple code:

first = $('ul#listticker li:first').html();


To use fade out effect and remove the element you can use this code:

.fadeOut('slow', function() {$(this).remove();});


Step 2: now you have to add the content saved into the var first to the end of the list:


You can use this simple code:

$('ul#listticker').append(first)


...where first is the var you used to save the content of the first element in the step 1.

Step 3: Now you have to move up the content of the list (My News 2 is now the first element of the list) and repeat the entire process from the step 1.




In Javascript code section of this tutorial I used setInterval() to repeat the process every 3 seconds (3.000 milliseconds). Ok, now take a look at HTML and Javascript code.


HTML Code
HTML code is really simple. The only thing you have to do is adding an <ul> list with ID = listticker and some list elements:

<ul id="listticker">
<li>My News 1</li>
<li>My News 2</li>
<li>My News 3</li>
<li>My News 4</li>
<li>My News 5</li>
</ul>

Remeber to add into the tag <head> of the page where you want to implement this ticker a link to jQuery:

<script type="text/javascript" src="jquery.js"></script>


Javascript Code
Take a look at the follow code. I implement 2 functions removeFirst() and addLast(). Each function contains five lines of code. Total lines for "conceptual" code: 10 lines! I promised! :)

<script type="text/javascript">
$(document).ready(function(){

var first = 0;
var speed = 700;
var pause = 3000;

function removeFirst(){
first = $('ul#listticker li:first').html();
$('ul#listticker li:first')
.animate({opacity: 0}, speed)
.fadeOut('slow', function() {$(this).remove();});
addLast(first);
}
function addLast(first){
last = '
  • '+
  • first+'';
    $('ul#listticker').append(last)
    $('ul#listticker li:last')
    .animate({opacity: 1}, speed)
    .fadeIn('slow')
    }

    interval = setInterval(removeFirst, pause);
    });</script>


    In the last line I used:

    interval = setInterval(removeFirst, pause);


    ...it calls the function removeFirst()every 3 seconds (3000 milliseconds) and in this way I create ad infinite loop.




    If you have suggestions to improve the code please leave a comment. Thanks!


    Related Posts
    If you are interested on other about this topic take a look at the following posts:

    - News ticker with horizontal scrolling
    - Fantastic News Ticker Newsvine-like
    - Automatic news ticker with vertical scrolling and Start/Resume options
    - Joomla! extension: super news ticker

    Bookmark and Share
    Digg this

    Simple PHP Twitter Search ready to use in your web projects


    After my previous tutorial that illustrated how to implement a super simple way to work with Twitter API (PHP + CSS) I received a lot of emails from my readers that asked to me to write a post about how to implement a simple Twitter search and display search results in a web page with a custom format. So in this tutorial I want to illustrate how you can implement that using a very useful Twitter Search API for PHP developed by David Billingham.

    Using this simple method you can obtain, just in some lines of PHP and CSS code, awesome results like this:



    You can download the source code at the following link and reuse it for free in your web projects just in some seconds!




    1. A little introduction
    In this package you'll find two PHP file:



    - index.php: the search page (search form + search results)
    - search.php: Twitter Search API for PHP

    You have to customize only index.php and your Twitter Search will be ready to be integrated into yor web projects in one minute!


    2. Index.php
    Take a look at index.php. This page contains a simple search form:

    <form action="index.php" method="submit">
    <input name="twitterq" type="text" id="twitterq" />
    <input name="Search" type="submit" value="Search" />
    </form>

    ...and some lines of PHP code:

    <?php
    include('search.php');
    if($_GET['twitterq']){
    $twitter_query = $_GET['twitterq'];
    $search = new TwitterSearch($twitter_query);
    $results = $search->results();

    foreach($results as $result){
    echo '<div class="twitter_status">';
    echo '<img src="'.$result->profile_image_url.'" class="twitter_image">';
    $text_n = toLink($result->text);
    echo $text_n;
    echo '<div class="twitter_small">';
    echo '<strong>From:</strong> <a href="http://www.twitter.com/'.$result->from_user.'">'.$result->from_user.'</a>: ';
    echo '<strong>at:</strong> '.$result->created_at;
    echo '</div>';
    echo '</div>';
    }
    }
    ?>


    $result is the array that contains search results. To display all elements of the array (search results) I used this simple loop:

    foreach($results as $result){
    ...
    }

    ... and to get a specific attribute of the array I used this simple code:

    $result->name_of_element

    The structure of a tweet contains the following attributes (take a look at the Twitter API home page for a full list):

    [text]: Text of the current tweet
    [to_user_id]: User Id
    [from_user]: User name
    [id]: Tweet Id
    [from_user_id]: User id
    [source]: Source of the current tweet
    [profile_image_url]: User profile image URL
    [created_at]: Date of the current tweet

    ...so, if you want to display the text of a tweet you can use this code:

    $result->text

    The following line of code get the text of the current tweet and convert a textual link into a clickable link:

    $text_n = toLink($result->text);

    That's all! Now download the source code, open and upload all files in your test server, open index.php and try to search for something!
    If you have some suggestion, please add a comment!




    Related posts

    - Super simple way to work with Twitter API (PHP + CSS)
    - Send messages from a PHP page using Twitter API

    Bookmark and Share
    Digg this

    How to implement a launching soon page with PHP and jQuery


    In this tutorial I want to explain how to implement a simple launching soon page using PHP and jQuery. What's a launching soon page? In general it's a page that informs the visitors of a website under construction about when the website is going to be online and allows them to leave their emails in order to be updated when the website is on-line. A typical launching soon page contains a countdown and a form that collects emails from interested visitors. In this tutorial I implemented a launching soon page like this:



    Take a look at the live preview here.

    This page is very simple to modify and customize using just some lines of CSS code. You can also add the logo of your company and all elements you want with some lines of HTML code. Download the source code of this tutorial you can customize and reuse in your web project for free!





    A little introduction
    How I said this package is ready to use and contains these files:



    - index.php: the launching soon page final interface (countdow + form)
    - config.php: enables database connection
    - insert.php: PHP code to add emails into a database table
    - js/jquery-1.3.2.min.js: jQuery framework
    - js/countdown.js: the countdown script


    1. index.php
    index.php is the final interface of your launching soon page. How I said it contains a countdown and a form to allow users to leave their emails.

    The countdown script
    In order to implement the countdown I used this dynamic countdown script that lets you count down to relative events of a future date/time. This future date, while the same for everyone, occurs differently depending on the time zone they're in. The result is here and it's fully customizable changing some lines of CSS code:




    The only thing you have to do is to add this line of code in the <head> tag of the page:

    <script type="text/javascript" src="js/countdown.js"></script>

    Then, in the tag <body> add the following lines of code to display the countdown:

    <div id="count_down_container"></div>
    <script type="text/javascript">
    var currentyear = new Date().getFullYear()
    var target_date = new cdtime("count_down_container", "July 6, "+currentyear+" 0:0:00")
    target_date.displaycountdown("days", displayCountDown)
    </script>


    To set a target date you have to change this line modifying July 6 and the hour 0:0:00 with your target date (for example 25 december):

    new cdtime("count_down_container", "July 6, "+currentyear+" 0:0:00")


    ...if your target date is 25 December the previous line becomes:

    new cdtime("count_down_container", "December 25, "+currentyear+" 0:0:00")


    If you want to change the style of the countdown you have to modify the following CSS classes:

    .count_down{...}
    .count_down sup{...}


    In particular .count_down{} changes the format of the numbers and .count_down sup{} changes the style of the text "days", "hours", "minutes".


    jQuery and the input form
    Ok, the countdown is ready! Next step: add this line of code to include jQuery in the <head> tag of the page:

    <script type="text/javascript" src="js/jquery-1.3.2.min.js"> </script>

    Now, in the tag <body> add a simple form with an input field:

    <form id="submit_leave_email">
    <input id="input_leave_email" type="text" class="input_bg" value="Add your e-mail address"/>
    <button type="submit" class="input_button">Update me</button>
    </form>


    ...and add this layer to display a custom message when an user submit the form:

    <div id="update_success">E-mail added!>/div>

    ...the result after the submission is here:



    The form with the input field disappears with a nice fade-out effect and a success message appears in its place. Now, in the <head> tag, after the line of code that includes jQuery, add this script to enable ajax functionalities to insert emails added from users into a database table without reload the page:

    <script type="text/javascript">
    $(document).ready(function(){
    $("form#submit_leave_email").submit(function() {
    var input_leave_email = $('#input_leave_email').attr('value');
    $.ajax({
    type: "POST",
    url: "insert.php",
    data:"input_leave_email="+ input_leave_email,
    success: function(){
    $("#submit_leave_email").fadeOut();
    $("#update_success").fadeIn();
    }
    });
    return false;
    });
    });
    </script>


    2. insert.php
    insert.php contains some lines of PHP code to insert an email address into a database table. In this example I created a table EMAIL with just one attribute "email". PHP code is very simple:

    <?php
    if(isset($_POST['input_leave_email'])){
    /* Connection to Database */
    include('config.php');
    /* Remove HTML tag to prevent query injection */
    $email = strip_tags($_POST['input_leave_email']);

    $sql = 'INSERT INTO WALL (email) VALUES( "'.$email.'")';
    mysql_query($sql);
    echo $email;
    } else { echo '0'; }
    ?>


    Now, remember to modify your database connection parameters in config.php and upload all files on your testing server. Than load index.php and see the result!

    Take a look at the live preview here.

    That's all! Download the source code of this tutorial you can customize and reuse in your web project for free! Leave a comment for your suggestions, thanks!

    Bookmark and Share
    Digg this

    Twitter API: How to create a stream of messages Monitter-like with PHP and jQuery


    This tutorial illustrates a very simple way to work with the Twitter API in order to implement a search in the Twitter public timeline and display search results with an animated stream of messages (tweets) similar to Monitter. In this example I used PHP, jQuery and a very useful Twitter Search API for PHP based on the work of David Billingham and actually developed by Ryan Faerman. This implementation is very simple to customize and integrate on your project. The result is something linke this:



    You can download the full code here and reuse it for free on your projects.



    I suggest you to take also a look at these posts:

    - Simple PHP Twitter Search ready to use in your web projects
    - Super simple way to work with Twitter API (PHP + CSS)
    - Send messages from a PHP page using Twitter API


    1. A little introduction

    This package contains the following files:




    - index.php: page with the search form + search results
    - search.php: PHP search
    - twitterapi.php: Twitter Search API for PHP
    - jquery/jquery-1.3.2.min.js: jQuery framework

    How it works? After submission the search form calls an ajax request to the page search.php that returns search results into an array. Each element of the array (every single tweet) appears into the div twitter-results with a nice fade-in effect. I set a delay between each tweet equal 2 seconds (2000 ms).



    I suggest you to take a look at Monitter, and download the full code to try this tutorial on your local host. Now, take a look at the code.


    2. index.php: HTML code

    HTML code is very simple. Copy the following code in the tag <body>:

    <div class="twitter_container">
    <form id="twittersearch" method="post" action="">
    <input name="twitterq" type="text" id="twitterq" />
    <button type="submit">Search</button>
    </form>
    <div id="twitter-results"></div>
    </div>

    ...and add into the tag <head> of the page a link to jQuery:

    <script type="text/javascript" src="jquery.js"></script>

    The result is a simple search form:





    3. search.php
    Now copy and paste the following code into search.php:

    <?php
    include('search.php');
    if($_POST['twitterq']){
    $twitter_query = $_POST['twitterq'];
    $search = new TwitterSearch($twitter_query);
    $results = $search->results();

    foreach($results as $result){
    echo '<div class="twitter_status">';
    echo '<img src="'.$result->profile_image_url.'" class="twitter_image">';
    $text_n = toLink($result->text);
    echo $text_n;
    echo '<div class="twitter_small">';
    echo '<strong>From:</strong> <a href="http://www.twitter.com/'.$result->from_user.'">'.$result->from_user.'</a>: ';
    echo '<strong>at:</strong> '.$result->created_at;
    echo '</div>';
    echo '</div>';
    }
    }
    ?>


    $result is the array that contains search results. To display all elements of the array (search results) I used this simple loop:

    foreach($results as $result){
    ...
    }

    ... and to get a specific attribute of the array I used this simple code:

    $result->name_of_element

    Take a look at this post for info about the search on Twitter.


    4. index.php: JavaScript Code

    Now take a look at the following JavaScript code that enables an ajax request for the search and display results into the page index.php with a fade in effect and a delay between each tweet equal to 2 seconds:

    <script type="text/javascript">
    $(document).ready(function(){
    var twitterq = '';

    function displayTweet(){
    var i = 0;
    var limit = $("#twitter-results > div").size();
    var myInterval = window.setInterval(function () {
    var element = $("#twitter-results div:last-child");
    $("#twitter-results").prepend(element);
    element.fadeIn("slow");
    i++;
    if(i==limit){
    window.setTimeout(function () {
    clearInterval(myInterval);
    });
    }
    },2000);
    }

    $("form#twittersearch").submit(function() {
    twitterq = $('#twitterq').attr('value');
    $.ajax({
    type: "POST",
    url: "search.php",
    cache: false,
    data: "twitterq="+ twitterq,
    success: function(html){
    $("#twitter-results").html(html);
    displayTweet();
    }
    });
    return false;
    });
    });
    </script>

    This is a very basic implementation you can modify to get a real-time stream of messages for example calling a new ajax request (to search.php) every time the current array with the search results is totally displayed in the page.

    That's all. If you have some suggestion please add a comment. Thanks!
    You can download the full code of this tutorial here and reuse it on your projects.



    Related posts
    - Simple PHP Twitter Search ready to use in your web projects
    - Super simple way to work with Twitter API (PHP + CSS)
    - Send messages from a PHP page using Twitter API

    Bookmark and Share
    Digg this