Getting started with Ajax

Ajax, so called a heaven for programmers and developers, since it doesn't requires the page to refresh to processing. Ajax was first introduced by Google back in 2005, and transformed into today's Google suggest, the best example and trademark of Google.

In this tutorial, I'll use back Google suggest to demonstrate getting started with Ajax, as I still feels it's the best example to demo Ajax. Let's get the party started!

Altogether, we'll need just 3 scripts to getting started with first Ajax, though it can be then optimized to be just 2 scripts, but I think 3 are better.

1. ajaxTest.php
First, create a file call it ajaxTest.php, this will contains some CSS, link to ajax javascript file, and basic design layout.

	body {
		font: 11px arial;
	}
	.suggest_link {
		background: transparent;
		padding: 2px 6px;
	}
	.suggest_link_over {
		background-color: #ccf;
		padding: 2px 6px;
	}
	#search_suggest {
		position: absolute; 
		text-align: left; 
		width: 45%;
		left: 280px;
		top: 195px;
	}		

Copy and the codes above and paste it on top of your ajaxTest.php, this will be some CSS. What we do simply set the body font size to 11 pixels Arial, .suggest_link is CSS for "Google suggestions" appear below the search box, .suggest_link_over is CSS for "Google suggestions" when mouse hover, #search_suggest is the main CSS for "Google suggest".


Next, copy the codes above and paste it just right below the CSS codes in ajaxTest.php just now. The codes above is only link the javascript file to ajax_search.js.



Google


Then, copy the codes above and paste it after your javascript just now. The codes above just have a simple Google-look design layout. Note that you'll have to have a div below your search box for "Google suggest" purpose.
Save your works, ajaxTest.php was done.

2. ajax_search.js
Now, it's show time for Ajax! All the codes in this file will be javascript, as it's save as ajax_search.js.

//Gets the browser specific XmlHttpRequest Object
function getXmlHttpRequestObject() {
	if (window.XMLHttpRequest) {
		return new XMLHttpRequest();
	} else if(window.ActiveXObject) {
		return new ActiveXObject("Microsoft.XMLHTTP");
	} else {
		alert("Your Browser Sucks!\nIt's about time to upgrade don't you think?");
	}
}

Copy the codes above and paste in your ajax_search.js, I mean on top. The codes above used to check whether ajax (javascript) has been enabled on users' computer. The first if() statement checks for Mozilla Firefox, Google Chrome, Apple Safari, Opera, and Internet Explorer 7. The second if() statement checks for dinosaur browsers, IE5 or IE6. Else, let user know their browser sucks, and it's about time to upgrade. You know I'm just kidding. Just for demo purpose, do not ever put this on production site!

//Our XmlHttpRequest object to get the auto suggest
var searchReq = getXmlHttpRequestObject();

//Called from keyup on the search textbox.
//Starts the AJAX request.
function searchSuggest() {
	if (searchReq.readyState == 4 || searchReq.readyState == 0) {
		var str = escape(document.getElementById('txtName').value);
		searchReq.open("GET", 'getName.php?name=' + str, true);
		searchReq.onreadystatechange = handleSearchSuggest; 
		searchReq.send(null);
	}		
}

Next, copy the codes above and paste in below your javascript just now. What the part above does is declare searchReq (XmlHttp), and implement searchSuggest() function, the whole about ajax transaction and processing. The if() statement checks if its readyState equals to 4 (final) or 0 (beginning), if hit then assign whatever user entered in the search box (document.getElementById('txtName').value) into str variable. searchReq.open("GET", 'getName.php?name=' + str, true); demonstrates uses ajax GET method, and the processing PHP file will be getName.php, in this case, and the last parameter is always TRUE, don't ask me why. searchReq.onreadystatechange = handleSearchSuggest; says that when processing, call another function, handleSearchSuggest. The last part searchReq.send(null); demonstrates send results back to interface. Note that GET method used, the parameter will be always null, otherwise if POST method, then will be argument followed by parameter passed in.

//Called when the AJAX response is returned.
function handleSearchSuggest() {
	if (searchReq.readyState == 4) {
		var ss = document.getElementById('search_suggest')
		ss.innerHTML = '';
		var str = searchReq.responseText.split("\n");
		for(i=0; i < str.length - 1; i++) {
			//Build our element string.  This is cleaner using the DOM, but
			//IE doesn't support dynamically added attributes.
			var suggest = '
'; ss.innerHTML += suggest; } } }

Then, copy the codes above and paste it below your javascript just now. The function above is called upon onreadystatechange. It checks if readyState equals 4 (finish processing), declares and assign "Google suggest" div (getElementById('search_suggest')) into variable ss, and initialize its innerHTML to empty. Then, split the responseText (results returned) and assign into str variable. For results returned, we concatenate them with ss.innerHTML.

//Mouse over function
function suggestOver(div_value) {
	div_value.className = 'suggest_link_over';
}
//Mouse out function
function suggestOut(div_value) {
	div_value.className = 'suggest_link';
}

//Click function
function setSearch(value) {
	document.getElementById('txtName').value = value;
	document.getElementById('search_suggest').innerHTML = '';
}

Lastly, copy the codes above and paste it in your ajax_search.js. The codes above shows example of javascript with CSS, it calls the javascript to set the CSS.

3. getName.php
Finally, the back end processing PHP file.

<?php
include 'includes/db_connect.inc.php';
$conn=db_connect();
if (isset($_GET['name']) && $_GET['name'] != '') {
$sql="SELECT field FROM table WHERE field LIKE '".$_GET['name']."%'";
$rst=mysql_query($sql,$conn)or die(mysql_error());
while($row=mysql_fetch_array($rst)){
  echo $row['field']."\n";
}
}?>

Create a file called getName.php, then copy the codes above and paste it inside. The codes above demonstrate establish database connection, query select results from database, then return the results, that's all.

Alright, you're about to graduate, have a try and hope you enjoy! :)

Comments

I use Ajax to build

I use Ajax to build interactive applications which help people learn how to lose weight fast and offer them helpful weight loss tips and ways to lose weight fast in simple ways.

qqq

Hundreds of links of london jewellery in stock,Top quality links of london sale collection,including necklaces,bracelets,earrings
links of london
links london
links of london jewellery

wedding dresses,wedding

wedding dresses,wedding gowns,bride dresses,bridesmaids dresses,evening dresses,bridal gowns,flower girl dresses
Wedding Gowns
Formal Gowns
Cocktail Gowns
Find the wedding dress designer and wedding dress that's right for you! Browse dresses from
Bridesmaid Gowns
Evening Gowns
View our selection of exquisite, handmade gowns and dresses for your wedding
Wedding Dresses, Wedding Shoes and Wedding Accessories from wedding shop, the UK's finest collection of designer wedding dresses.
Use the wedding dress and
cheap wedding
wedding dresses
wedding shop