How about a taster on the cool things AJAX can do

I simply love the fact you can use PHP and AJAX together to get more of a desktop feel to a web application. I use it more and more for my client's apps.

This script contains three files (example.html, ajax.php & jquery.js ) You will need to download jquery.js and put it on your server along with the example.html and ajax.php files. Dont forget to rename it jquery.js as the file name you download will contain the current latest version.  (or just download the zipped files!)

You can see it in action here.

When the files are put on a server that can run PHP, they will function as a simple AJAX example using jQuery and PHP. Great things have to start somewhere!

For this basic example, the form will contain one field, and the validation will simply check to see if that field is empty. This script was created to be very simple, and very easy to repurpose for various projects.

example.html – The example file is the file that will be loaded in the browser. It contains our basic HTML setup, jQuery include, form elements, and AJAX call.


 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
 <title>Example PHP and AJAX working in harmony</title>
 <script type="text/javascript" src="/jquery.js"></script>
 <ul id="box1">
 <li>Put anything you want in the form field below.</li>
 <form id="form1">
 <input type="text" name="field1" id="field1">
 <input type="submit" name="submit" id="submit" value="Submit Form">
 $('#form1').submit(function(event) {
 type: 'POST',
 url: 'ajax.php',
 data: $(this).serialize(),
 dataType: 'json',
 success: function (data) {


The AJAX file is the engine behind the example file. It will do all of the form processing and return an error or success message based on the results.


    class ajaxValidateExample {

 		function formValidate() {
 		//Put form elements into post variables
		//(this is where you would sanitize your data)
 		$field1 = @$_POST['field1'];
 		//Establish values that will be returned via ajax
 		$return = array();
 		$return['msg'] = '';
 		$return['error'] = false;
 		//Begin form validation functionality
 			if (!isset($field1) || empty($field1)){
 			$return['error'] = true;
 		$return['msg'] .= 'Error: Field1 is empty.';
 		//Begin form success functionality
 		if ($return['error'] === false){
 		$return['msg'] = 'Success Message - '. $field1 .'';
 		//Return json encoded results
 		return json_encode($return);
 	$ajaxValidate = new ajaxValidateExample;
 	echo $ajaxValidate->formValidate();

Notice that it passes back an array ($return) that has two keys: “msg” and “error”. You can add as many keys as you’d like to this array, and use them on the front end (example.html) any way you like.

In this example, we’re just using “msg” to output the results into the list about the form.

click here for the source code. (including the jquery.js file)