Using Ajax to validate form

Posted February 6th, 2010 in Javascript, PHP, Source Files, Uncategorized by Jimi Sulaiman

There are times where you need to validate a form to a data stored in a database without the need to submit the form beforehand. The solution -

Ajax (shorthand for asynchronous JavaScript and XML).

For example, you are creating a user registration form where obviously, the username to choose from needs to be unique. Instead of validating the username after form submission, wouldn’t it be much friendlier if the form can validate itself  from the server asynchronously in the background from a simple event such as on submit or unfocus event?

In this post, I will be showing how you can the validate with Ajax using PHP/MySQL as your back-end. A table called user is created in the MySQL database which contains some dummy usernames.  When user enters a username existed from this table, the form will prompt an error with message “Username already taken. Please try a different username.”

What you need:

- jQuery 1.4, my favourite javascript library. Click here to download
- jQuery plugin, Validation 1.6. Click here to download
- PHP and mySQL enabled web server (for this example, I’m using PHP 5 and MySQL 5)

You’ll gonna need two files:

- form.php < this will be your form
- check_username.php < this will check  if data exist in the user table in your MySQL database

Link jQuery and the plugin to the form page first.  You can refer to the source file(link at the bottom of this post) if you are not clear on how to do this.  Then add the javascript code below and you’re done on this page.
I’ve commented the code below to explain what each line does.  I’m not gonna touch on the Validation plugin here but if you are interested, you can view its Documentation available from the download site.


$(document).ready(function() {

    $("#myform").validate(); //apply the validation plugin to your form

	$("#username").rules("add", {
		 remote: {
			url: "check_username.php", //place the PHP here
			type: "post", //using the post method to send data (you may also use the get method)
				data: {
				  username: function() {
					return $("#username").val(); //get the value from the text input
				  }
				}
			},
		 messages: {
		   remote: "Username already taken. Please try a different username." //set the message you want to display
		 }
	});

});

The next step is to create the PHP page that checks if the user existed.  Because the validation only works with Boolean values,  so you will need to code the page to return the text true if username doesn’t exist or false otherwise.  Here is the search Query in PHP for this example.

$query="SELECT * FROM users WHERE LOWER(username) = '$username'";
$result=mysql_query($query);
$num=mysql_num_rows($result);
//check if number of users with the username exist more than 0
if($num >0){
echo "false";
}else{
echo "true";
}

Test the form by typing any username that has already existed, your form should be showing an error message next to the username input as shown in the demo below.

Click here to view live demo

Get the complete source file: Ajax Form Example (99)

  • Share/Bookmark

Ajax/PHP Message Board with jQuery

Posted December 23rd, 2009 in PHP, Source Files, Website by Jimi Sulaiman

A product from last weekend boredom – a PHP based message board with jQuery based UI and mySQL database.  My aim was to create a very simple message board that is easy to use  and easy to implement accross my web projects.  I’ve also added a little security with Captcha to reduce spam.

What you need:
- A PHP enabled webserver with mySQL database. You need to set this up first.

To install:
- Configure the config.php file
- Run the data.sql file from your mySQL database
- Upload all files into your webserver and you’re done

Demo: http://www.jimisulaiman.com/message_board_php

Download source file: JS Message Board (212)

If you like this file, or it has benefited you, please comment :)

*GNU General Public License applies. This is free stuff so do not expect any support.

  • Share/Bookmark

Getting Random Image with specific width from mySql

Posted October 28th, 2008 in Codes, PHP by Jimi Sulaiman

This class written in PHP is very useful when you want to display random images in your website. I’ve used this class to generate the Homepage image for an image gallery website. Because the homepage requires the image to be large and must follows specific width to caters the design, in this example 800px, then the class will need to have the following method:

Get random row from uploaded images > get the filename and caption> check the file’s width > call the class from the design area.

The PHP class:

<?PHP
class getRandomImage {
public $file;
public $caption;

function checkWidth($file){
list($width, $height, $type, $attr) = getimagesize($file);
if ($width>=800){ //image's width must be at least 800px
return true;
}
return false;
}

public function getImage(){
$uploadpath = 'images/gallery/'; //path of uploaded images
$width = 0;//Get random row from the MySql database
$offset_result = mysql_query( " SELECT FLOOR(RAND() * COUNT(*)) AS `offset` FROM `gallery_image` ");
$offset_row = mysql_fetch_object( $offset_result );
$offset = $offset_row->offset;
$result = mysql_query( " SELECT * FROM `gallery_image` LIMIT $offset, 1 " );
$row=mysql_fetch_object($result);
if(mysql_num_rows($result)>0){
$file=$row->filename;
$caption=$row->caption;
$this->setCaption($row->caption); //set caption
$file=$uploadpath."".$file;

if (!$this->checkWidth($file)){ //if width not satisfied, get another row
return $this->getImage();
}
}
return $file;

}
//getters
public function getCaption() {
   return $this->caption;
}
//setters
public function setCaption($caption) {
   $this->caption = $caption;
}

}
?>

Then call the method from where you want to place the image. Here I will set the image as the DIV background.

<?PHP
$getRandomImage  = new getRandomImage;
?>
<div class="mainImage" style="background:url(<? echo $getRandomImage->getImage(); ?>)">
<?PHP
//get caption
if($getRandomImage->getCaption()!=''){
echo "<div class=\"caption\">".$getRandomImage->getCaption()."</div>";
}
?>
</div>

Thats it. If you have a better suggestion or cought a bug, please comment :)

  • Share/Bookmark