It was a long time since my last post, so I thought of posting something interesting today: A tutorial that will show you how to use AJAX with Jquery to call PHP scripts. Take a coffee, it’ll be a long read
You may want to check what we are going to build before diving into this tut.
- Designing the form
- The database and the PHP code
- Ajax Calls
- Optimization and security
- The End
First step is to design a nice looking form. The form has 3 inputs: Two text boxes and one button. We can either user tables or lists. But I prefer to use lists and labels since they are SEO friendly.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Ajax Web Form</title>
<link href="style.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div id="wrap">
<form id="ajaxform">
<div class="form_description">
<h2>Ajax Web Form</h2>
<p>
This is an example Ajax form. It checks if the username is available or create a new username.
</p>
</div>
<ul>
<li id="username_check">
<label class="lbl">
User Name (Availibility)
</label>
<div>
<input class="txt_input" id="txt_checkuser" type="text" maxlength="255" value=""/><p class="hint"> <img src="img/ok.png" /> User name Available</p><p class="hint"><img src="img/no.png" /> User name already used</p>
</div>
</li>
<li id="username_add">
<label class="lbl">
Add UserName
</label>
<div>
<input class="txt_input" id="txt_adduser" type="text" maxlength="255" value=""/>
<p class="hint"> <img src="img/ok.png" /> User name added successfully</p><p class="hint"><img src="img/no.png" /> Error while adding User name</p>
</div>
</li>
<li class="buttons">
<input id="submit_form" class="btn" type="submit" value="ADD" />
</li>
</ul>
</form>
</div>
</body>
</html>
Now let’s add some CSS code to make it look a little better and more inducing.
#wrap
{
width: 550px;
height: 250px;
margin: 75px auto;
}
.btn
{
float: right;
width: 150px;
height: 35px;
border: 1px solid #000004;
background-color: #A8CBFE;
cursor: pointer;
}
BODY
{
margin: 0;
font-family: "Lucida Grande", Tahoma, Arial, Verdana, sans-serif;
font-size: small;
padding: 0;
}
H2
{
clear: left;
font-size: 160%;
font-weight: 400;
margin: 0 0 3px;
}
#ajaxform
{
padding: 10px 25px 50px;
border-top: 40px solid #A8CBFE;
margin: 0;
border-left: 1px solid #B9B9C5;
border-bottom: 1px solid #B9B9C5;
border-right: 1px solid #B9B9C5;
}
.form_description
{
border-bottom: 1px dotted #999999;
margin: 0;
padding: 0;
}
FORM LI
{
display: block;
margin: 0;
padding: 4px 5px 2px 9px;
position: relative;
}
#username_add:hover
{
background-color: #DAFCBF;
}
#username_check:hover
{
background-color: #DAFCBF;
}
#username_check
{
}
FORM UL
{
font-size: 100%;
list-style-type: none;
margin: 0;
padding: 0;
width: 100%;
}
.btn:hover
{
background-color: #A9DAFD;
}
Our form should look like this (Oh, for the icons they are the famous FAMFAMFAM icons
)

You should have noticed the hints. They are visible since we are going to hide/show them using Jquery.
So we’ll add some additional code to load the library and hide the hints.
Add this code to the “head” of the page. Don’t forget to download Jquery, I used version 1.3.2 as of the release of this tutorial.
<script src="jquery.js" type="text/javascript"></script>
<script src="script.js" type="text/javascript"></script>
After, create a new javascript file called “script.js” and add the following code. It’ll hide the hints when the page loads.
$(document).ready(function() {
// Hide all the hints
$('.hint').hide();
});
Later on, you’ll discover that we’ll load the hints from the PHP script using Jquery. Nevertheless, we’ll need a hint stored on HTML in case AJAX can’t connect to the server.
Next we need to set up a database and a table to store the user names. I named my data base “mydatabase” and the table “users”. Here’s the SQL code to generate the table. It’ll create two rows.
-- phpMyAdmin SQL Dump
-- version 3.2.1
-- http://www.phpmyadmin.net
--
-- Host: localhost
-- Generation Time: Aug 18, 2009 at 08:13 AM
-- Server version: 5.1.37
-- PHP Version: 5.3.0
SET SQL_MODE="NO_AUTO_VALUE_ON_ZERO";
--
-- Database: `mydatabase`
--
-- --------------------------------------------------------
--
-- Table structure for table `users`
--
CREATE TABLE IF NOT EXISTS `users` (
`ID` int(4) unsigned NOT NULL AUTO_INCREMENT,
`username` text NOT NULL,
PRIMARY KEY (`ID`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=0 ;
--
-- Dumping data for table `users`
--
INSERT INTO `users` (`ID`, `username`) VALUES
('omarabid'),
('anotheruser');
In order for the query to work correctly, log in to PHPmyadmin, select a database and then click “SQL” tab. Paste the code and hit the “Go” button.

Now we need to create a PHP script. It will be called later using Jquery. We’ll use the OOP methodology. So we’ll create a user class and two function “checkuser” and “adduser” that return either true or false.
The user Class
// User Class
class user {
var $_un;
function user($un) {
$this->_un = $un;
}
function adduser() {
// Checks if user exists
if ($this->checkuser() == true) {
return false;
} else {
// Try to add the user
$qr = mysql_query("INSERT INTO users (username) VALUES( '".$this->_un."' ) ");
// Return True or False
if ($qr == 1) {
return true;
} else {
return false;
}
}
}
function checkuser() {
// Query the DB
$qr = mysql_query("SELECT username FROM users WHERE username = '".$this->_un."'");
$res = mysql_fetch_array($qr);
if ($res == NULL) {
return false;
} else {
return true;
}
}
}
The PHP script
The script is composed of three parts: The Class, the Mysql Connection and the code (that will execute the transactions).
In the top, we’ll place the user class. Next, we’ll connect to the database. After, we’ll grab HTTP post information and execute actions from them.
// Add the user class here
// Disable caching to prevent unwaited results
header("Cache-Control: no-cache");
// Connect to Mysql
$conn = mysql_connect('localhost', 'root', 'your-password') or die('Could not connect to mysql');
mysql_select_db('mydatabase') or die('Could not connect to DB');
// Retrieve data from HTTP Post
$action = $_GET['action'];
$username = $_GET['username'];
// Create a new user object
$newuser = new user($username);
// Parse HTTP header information
if ($action == 'add') {
if ($newuser->adduser()) {
// User Added
echo '<p class="hint"> <img src="img/ok.png" /> User name added successfully</p>';
} else {
echo '<p class="hint"> <img src="img/no.png" /> User name was not added</p>';
}
} elseif ($action == 'check') {
if ($newuser->checkuser()) {
// User Already exists
echo '<p class="hint"> <img src="img/no.png" /> User name already exists</p>';
} else {
echo '<p class="hint"> <img src="img/ok.png" /> User name available</p>';
}
} else {
echo "No Action Is defined";
}
// Close Connection
mysql_close($conn);
To make the script work, you need first PHP and Mysql running either on a host or on your local machine.
After, create a Mysql database and add the “users” table to it (as described above).
Now, it’s time to tweak the script. Change the host, username, password and database values. Next, place the script in your host root or a folder and execute it. If nothing “No Action Is defined” shows, then the connection worked correctly.
To try the script and check if it functions correctly, type “script.php?action=check&username=typehere”.
It’s time we implemented the AJAX feature. We have two inputs to check: The first one after the user completes typing, the next when the user clicks the “Add” button.
$(document).ready(function(){
// Disable caching to prevent unwaited results
$.ajaxSetup({
cache: false
});
// Check un availability after typing a name
$("#txt_checkuser").change(function(){
// Store the username in a variable
var jq_username = $("#txt_checkuser").val();
// Prepare the link
var link = 'http://localhost/AJAX/user.php';
$('div #checkuser_hint').load(link, "action=check&username=" + jq_username);
});
// Add a user name
$("#submit_form").click(function(){
// Store the username in a variable
var jq_username = $("#txt_adduser").val();
// Prepare the link
var link = 'http://localhost/AJAX/user.php';
$('div #adduser_hint').load(link, "action=add&username=" + jq_username);
});
});
As you see, first we disabled the cache. Second, we bind the change event to the txt_checkuser input. This will make the code run when the user change focus from the input. Third, we bind the button to the click event.
Now everything is working correctly and as it should.
Security
The script and form works, but we didn’t take care of malicious people and hackers in the web. We need to secure our form against SQL injections.
If you are new to them, here’s a simple example.
This code queries the database using the variables directly.
// Query database to login any matching user
$query = "SELECT * FROM users WHERE user='{$_GET['username']}' AND password='{$_GET['password']}'";
mysql_query($query);
?>
Now, let suppose someone entered the following.
Username: topuser
Password: ' OR ''='
The mysql query will become
$query = “SELECT * FROM users WHERE user=’topuser’ AND password='' OR ''=''”
Resulting in full access to any accout!
To prevent SQL injection, PHP offers a function called “mysql_real_escape_string”. Here’s how we can implement it.
// First query
$qr = mysql_query(sprintf("INSERT INTO users (username) VALUES( '%s' ) ",mysql_real_escape_string($this->_un)));
// Second query
$qr = mysql_query(sprintf("SELECT username FROM users WHERE username = '%s' ",mysql_real_escape_string($this->_un)));
Optimization
We can optimize our form a little bit. We can for example check for user input, server availability or any other thing.
For example, while I was trying it; I noticed that when I check for an available username and then add it, the available notice don’t change to unavailable even if you edit the username and retype it.

As you see, the “User name available” doesn’t change since text didn’t changed. So Jquery don’t fire the function another time.
To fix this little issue, we can add this conditional block when the user hit the add button
// If the username is the same as checked, change the notice
if (jq_username == $("#txt_checkuser").val()) {
var link = 'http://localhost/AJAX/user.php';
$('div #checkuser_hint').load(link, "action=check&username=" + jq_username);
}
We can never finish optimizing and securing our scripts and code; but we try to do our best
In this tutorial, you learned how to create a simple web form, write PHP code to query a database and use AJAX with Jquery to dynamically link between the form and the script.
I tried to explain Step-By-Step, I also made an online example available for preview; you can also download the source code.
Now let me hear critics, suggestions, bugs....
{ 0 comments }


Fighting Web SPAM
by Omar Abid on June 18, 2009 · 1 comment
in internet
In the few past days, I was busy to keep up with the blog. By mistake, I disabled moderation on blog comments; results: more than 100 comments, totally SPAM.
Bloggers are happy with comments, this mesure the user interaction with the blog post and the success of the writer in attracting attention, but when it happens to be SPAM, then it’s not good and it’s even worse: lose time and bandwidth.
How you get SPAMMED?
How to solve those problems?
If you are using Wordpress as a blogging platform, the most popular platform, then a few steps are required to fully protect yourself. Even if they won’t protect you from SPAM for %100, they’ll decrease the number efficiently and increase comments quality
To do it and stay compatible with every template you install, just install and activate this simple “nofollow” plug-in. “nofollow” tags, will make searh engines dismiss comment links. If so, SPAMMERS won’t be interested on your links.
Moderate your comments, if you have 100 or more in each post, you can disable them and create a forum where your users can discuss the blog post. Good comment moderation will discourage SPAMMERS to attack your blog.
Askimet is very useful so turn it on, it’ll need 5 minutes if you don’t have a Wordpress API key (don’t worry, all you need is a wordpress.com account)
This is another important step, SPAMMER may not look for links but for traffic, even if it’s small from one comment, it will be big from thousands. Adding a good captcha will help blocking the malicious boots.
When to use captcha: Only when you got attacked, I have been attacked on a blog last year, spammers sent boots that change ip, user name, email and submit hundred, yet thousands of comments! Askimet may protect against SPAM and catch them, but the quantity of comments attack will eat your bandwidth and may cause a huge traffic usage.
Conclusion: If you got spammed, it’s most likely your fault! If you want to help fight SPAM, just begin by securing your system and your code.
{ 1 comment }