Ajax: Unlocking The Code

Scribbled by Cody on the August 15th, 2007

Ajax- Son of Telamon and Periboea and king of SalamisAsynchronous Javascript and XML is a combination of technologies all under the umbrella of ajax. Like an all powerful god of cleaning, Ajax wills scrub your site of ugly user interface issues. Okay, enough with the lameness…

When you’re ready to sit down and implement an async javascript call you’re going to ask yourself “where do I start?” Well, everyone has a different answer and, really, it depends on how serious you are into knowing the right answers. You can copy and paste a standard ajax code block and be on your way in minutes (if you know javascript).

For instance…

Acetaminophen side effects
Clomipramine
Fiorinal cod
Cialis levitra vs
Keppra for seizure
Finasteride manufacturer tablet
B hydrocortisone neomycin polymyxin sulfates
Humulin n
Piperacillin
Effects pravachol side
Lipitor zocor
Lamictal lamotrigine
Tamoxifen
Pioglitazone hcl
Lasix dosage
Spironolactone hirsutism
Spironolactone hair loss
Vasopressin
Add amoxil link
Mometasone furoate cream
Venlafaxine withdrawal
Albuterol ipratropium
Propafenone hcl
Voltaren
Hydrocodone guaifenesin
Neurontin and depression
Buy cheap fioricet
Lunesta vs ambien
Thiamine disulfide
Ketoconazole tablet
Flomax avodart
Arthrotec medication
Can chloramphenicol die dog from overdose
Benadryl dosage for infant
Viagra cialis levitra
Mirena iud
Augmentin effect side
Lamisil
Alesse 21
Generic hyzaar
Levitra
Alprazolam online
Zetia side affect
Ampicillin sodium
Zolpidem tartrate
Butalbital compound
Enalapril line
Meperidine promethazine
Hydroquinone tretinoin
Generic minoxidil
Medicine bentyl
Acetaminophen toxicity
Indocin side effects
Albuterol usp
Drug more omnicef use
Dopamine function
Senna matsuda
Loperamide hydrochloride
Buy crestor online
Nor epinephrine
Vermox mebendazole
Effects insomnia side valerian
Senna extract
Belladonna delphinium
Piperacetazine
Dilaudid iv
Trileptal weight gain
Phenergan with codeine
Alka-Seltzer
Guaifenesin protocol
Cream ketoconazole use
Hydroxyzine for dog
Trazodone desyrel
Ethanol
Digitalis foxglove
Enter belladonna
Trifluoperazine
Doxycycline for acne treatment
Carbohydrate lipids
Tri levlen 28
Ativan vs xanax
Chlorpromazine thorazine
Provigil 200 mg
Bupropion loss weight
Buy vicodin
Droperidol
Ad nizoral
Ceftizoxime
Crestor drug
Side effects from lipitor
Accolate
Benadryl dose dog
Dianabol dosage
Best esomeprazole generic nexium price
Gentamicin sulfate eye drop
Cream verapamil
Coupon lunesta
Valacyclovir hydrochloride
Vytorin medication
Paroxetine side effects
Topical tretinoin
Lexapro information
Codeine phosphate
Augmentin xr
Chemical formula for thiamine mononitrate
Demerol side effects
Law firm terbutaline
Didrex
Nalorphine
Percocet 10 mg
Aldara
Premarin prempro
Zafirlukast
Concerta medication
Drug actonel
Quinapril
Nifedipine and pregnancy
Hydrocodone order
Spironolactone
Lipitor pravachol
Risperdal side effects with child
Benefit of multivitamins
Acid esters fatty lipids polyglyceryl
Gift massage mineral oil
Trimethoprim side effects
Cymbalta and weight gain
Child benadryl dosage
Misoprostol en mexico
Trazodone sleep aid
Etodolac lodine
Arthrotec 50mg
Danaparoid
How to smoke opium
Phenergan and vicodin
Dexamethasone suppression test
Generic accupril
Bacitracin ophthalmic
Levaquin
Buy diazepam online
Obagi tretinoin
Cipro information
Acetazolamide diamox effects side
Nitroglycerin medication
Ic doxycycline
Adderall dosage
Aspirin robert
Novo paroxetine
Hydrochlorothiazide tablet
Avoid coumadin food while
How does digoxin work

You can read up on everything you’ll ever need to know about AJAX or break open an editor and start coding. I prefer the second method, while working my understanding after practicing it’s implementation (but I often think backwards).

Let’s dump some code on ya:

status = true;
if( window.XMLHttpRequest ) {
	httpRequest = new XMLHttpRequest();
} else if(window.ActiveXObject){
	httpRequest = new ActiveXObject("Microsoft.XMLHTTP");} else {status	=	false;}

This block of code initializes the asyncronous javascript procedures by asking your browser for the ‘object’ that is best suited for transporting data. If your browser can create an XMLHttpRequest object, than it is not running Internet Explorer-that filters out the one from the many.

The XMLHttpRequest object is the single most important part of the process because it holds the code to sending http requests to a remote host inside of a javascript. If you’re running in InternetExplorer you’ll hit the second logical block which asks about ActiveXObject.

Using either object type, you’ll be granted the same defined interface. Why didn’t they standardize? Who knows, why didn’t they standardize how they all work with CSS? It’s a mystery.

This block of code will be seen in almost every (working) implementation of an Ajax procedure. Without the ability to send asynchronous message you’ve lost the “a” in ajax, right?

Now, from here we’ll move to the next logical block of code:

if( status ) {
	httpRequest.onreadystatechange = function() {
	if( httpRequest.readyState == 4 ){ // 4 = LOADED AND READY!
		if (httpRequest.status == 200) {
 			// Do Stuff
		}
	}
}	// end function()

Alright, if the status is true than we found our async object and can move on to readying it for goodness. This is where we’ll fill in our onreadychange function callback. Stop. What? What’s a function callback?

You will hand the async object httpRequest a function to call when it has successfully received data back from the remote host. Remember, async actions happen ‘while’ other things are happening. That means, when you leave this javascript function there is a high degree of probability the request you’ll be sending to the remote host is still pending.

When the process of connecting to the remote host and requesting data is completed your function is called back to action. When you are called back the httpRequest object sets its ‘readystate’ and ’status’ from the prior http query, these are important because you only want to react to a successful result, right?

If you want to read more on readystate please checkout devguru. Otherwise, we continue. A readystate of 4 means the request was “COMPLETED” but we’re not sure if it was successful or not. That’s where the ’status’ member comes into play! If the status is 200 this stands for “200 OK” status code from the hypertext transport protocol specification (aka http specification). Similar to code 404 which is for “page not found.”

Once you’ve received a readystate of 4 and a status of 200 you know you’re ready to proceed with modifying any data you want. This is where we state // Do Stuff

What stuff? That’s up to you! Typically, you query to a remote host to grab a portion of some HTML to stuff into a division. We’ll cover that later because what you do, at this point, is secondary to getting the request completed.

Now we setup the actual query… we do this second because all we’ve defined, so far, is the callback to what function to execute once the query is complete. So here is the query code:

var url = "/testme.php?ajax=true&username=joe";httpRequest.open( 'GET', url, true );httpRequest.send( null );

Too easy? Let’s break it down, first we have the variable url, this URL is the one we’re going to fetch asynchronously. Please note: the page must be on the same domain as the page calling the javascript. This is important because trying to access a different site in your javascript is a breach of security and IE or FireFox’s error console will tell you as such (or things just won’t work). Accessing another site from the current sites content is a great way to obtain viruses and other bad cross-site scripting issues so it’s not allowed.

So, once you’ve formulated your URL (you can use form data if you need to send a dynamic request) you can send your GET request (or POST request if you change the first argument to open()) and expect some results! The open() method to your httpRequest object takes up to five parameters, we’re only using three (the last two are username and password). The first is the type of request, usually ‘GET’ while the second is the URL and the third being ‘true’ meaning “we want to do this asyncronously otherwise you’re not really doing the ‘a’ in ajax again.

The send() method of httpRequest will send out your GET request async to the remote host. It can take one parameter but you’ll usually always use null. Just accept that as truth until you really need to delve into the guts of the async object.

That’s it!?

Now you know how to asyncronously send url requests to your server to gather new data. You’ve got a lot of power at your disposal now, to do with as you please. The trick is in the details and this is why PHP and web developers get paid the big bucks… you can send ajax queries all day but if your backend server doesn’t understand what you’re asking for, it will do you no good.

You can do one of two things: write your own php parser to a specific GET or POST request, or try using an ajax framework. I’ve never used a framework so I can’t help you there, but non-developers may need to go that route.

So, what ’stuff’ do you do when you receive a successful async request? You can use it for form validation ‘on the fly’ for registration pages, that’s one case. Where the user starts typing in a username and you’re asyncronously checking the database to see if the username is taken and responding with a simple message.

For instance, you may write a query that asks if a username is taken by sending a GET url like “/usercheck.php?user=admin” which is composed like:

var userfield = 	document.getElementById('username');
var url = "/usercheck.php?user=" + userfield.value;

In this example we target a theoretical input field with an ID of username and hand its value off to the URL (userfield.value should be equal to whatever the user has typed into the ‘username’ input field on a form). You could then write a php process (inside of usercheck.php) which takes the username passed and checks for its existance in your database. That code is beyond the scope of this article.

Your usercheck.php script could simply return “yes” or “no” in regards to the users existance! Where is the response from our request? It’s hidden in the httpRequest object upon returning from the query and calling our onreadystate callback!

if (httpRequest.status == 200) {
	// Do Stuff
	if( httpRequest.responseText == "yes" ) {
 		// username exists!
	} else {
		// username is free to use
	}
}

The responseText holds whatever your php script sent back in response to the async query. It could also be a full block of HTML to insert into a website, similar to how digg.com works or how the poll on simplyfired.com works (I know that, because I wrote the poll on that site from scratch).

Let us say you wanted wanted to update a division tag with new content from the results of a async javascript http request. The output from our theoretical php script is:

<span id=’message’>Hello, I think you’re cool</span>

Useless text, I know, but fits well into our example. Now let’s say the page that has already been rendered to the user and their browser is:

<div class=”helloMsg”><span id=’message’>Your message goes here</span></div>

We’ve readied the division for our dynamic message change. Our goal, to change everything between the division tags with the async results shown above. In between our check for status code 200 (where I commented //do stuff) we can place:

if( httpRequest.readyState == 4 ){ // 4 = LOADED AND READY!	if (httpRequest.status == 200) { 		document.getElementById( 'helloMsg' ).innerHTML = httpRequest.responseText;	}}

And that line does it all! It finds the element listed by id ‘helloMsg’ which happens to be our division and changes all the code inside the tag (hence, ‘innerHTML’) with the response from the server. After this operation the user will see, right before their eyes, a change in the content on the website.

Amazing? To the user it is! Instead of a span tag you could have injected an image, or a change in ‘vote’ count (in the case of digg.com) or the poll results in the case of simplyfired.com. And, if you’re not sure how the magic works, the beauty of javascript is it’s public to all! You can see my javascript on simply fired by open ing poll.js right on their site. The magic unfolds before thine eyes!

These are just a few examples to how you can utilize Ajax for cool effects. Just remember, you should really use ajax for cool neat-o features, eyecandy and administrative functionality. Don’t go ajaxifying your entire site (yeah, I just made a new verb) just because you now have knowledge you’ve never had before.

Use it sparingly and where appropriate. If you’re still confused on how it works, you can find a site that uses ajax and ‘view source’ and start poking around their javascript files looking for an httpRequest object and see what they did to make the magic happen.

 

 Posted in Development, ajax


Comments are closed.