Easy Ajax: From Web 1.0 to Web 2.0 in 5 steps

September 30th, 2008  |  Published in Uncategorized

Ajax is a method used to update a page with JavaScript, without reloading the page. This is the basis of all web applications.
ajax in 5 steps
The main ways to update a page are as follows:

  • With an XML HTTP Request
  • Using a hidden Iframe
  • Using a hidden image
  • Using a plain old <script> tag.

In this tutorial we will be using the <script> tag, as it is the easiest, cross browser and is the most logical.

Our aim is to process the user’s data (their name) on the server, without the user having to submit a form and load another page.

Take a look at the View the completed ajax demo if you’re feeling sneaky.

Step 1: Set up the HTML

Our basic HTML is as follows:

<html>
	<body>
		<form name="ajaxform" onsubmit="return doajax()">
			<label>
				What is your name?
				<input type="text" name="yourname" id="yourname">
			</label>
			<input type="submit" value="Submit">
		</form>
		<h2>Results</h2>
		<textarea id="results"></textarea>
	</body>
</html>

(Doctype etc removed here to be concise)

Step 2: Requesting a script

When the form is submitted, we want it to load a server side script and process our data. The doajax() function below will load a server side script (ajax.php) with the contents of the form.

function doajax() {
	// get our data
	var yourname = document.getElementById("yourname").value;
	// create a new script element
	var ajaxscript = document.createElement('script');
	// set the data as a parameter
	ajaxscript.src = 'ajax.php?yourname=' + yourname; to the script's source
	// load the script
	document.getElementsByTagName("head")[0].appendChild(ajaxscript);
	// stop the form from submitting
	return false;
}

Step 3: Processing the data

This is where the clever stuff happens. Normally you’d use the form data, look it up in a database and return a response. We’ll keep this example as simple as possible, so it should be easy to adapt and extend. This code is written in PHP, but you can use any language you want.

This code takes the “yourname” request parameter and converts it to upper case. Of course, this could easily be done with JavaScript, but that’s not the point of this tutorial.

loadResponse('<?php print addslashes(strtoupper($_REQUEST["yourname"])); ?>');

Yes, it’s just 1 line. The PHP here is writing the JavaScript. If you run ajax.php?yourname=Dave it will generate the JavaScript:

loadResponse('DAVE');

The important thing to note is that the server side script is taking in the request parameter, processing it, then writing out some JavaScript.

Step 4: Displaying the data

As you can see form step 3 above, a function loadResponse() is being called by ajax.php. We need to create this function and do something with the data.

function loadResponse(responseString) {
	document.getElementById("results").value = responseString;
}

Step 5: Extend it!

I lied: there are only really 4 steps. This code is very basic and could do with some error checking.

Further ideas to try:

  • Make the JavaScript unobtrusive. The code should check whether the browser supports specific functions and only “ajaxify” the page is it passes. If not, it should gracefully degrade to plain HTML.
  • Implement caching. Store frequent requests in the browser, then load them locally to make it look like your Ajax page is instantaneous.
  • Add onkeyup="doajax()" to the input field. This will send of a request to ajax.php a lot, so is not recommended on its own!
  • Add a timer to the page, so the page is not updated more than once in 200ms
  • After playing with the page a bit you’ll notice there are many script tags. These should be removed.
  • Cheat with a JavaScript library
  • Learn how to do it with XML HTTP Request (post coming soon)

View the completed demo here. Any questions? Comments? Errors?

Son of Suckerfish dropdowns in jQuery

September 22nd, 2008  |  Published in Uncategorized  |  2 Comments

If you’ve never heard of Suckerfish menus, they’re a simple way to get drop-down menus working in IE6. IE6 has lacks many features of modern browsers. One of the most important missing features is the ability to define hover pseudo classes to elements other than A (anchor links). The original Suckerfish dropdown code from A List Apart is as follows:

startList = function() { if (document.all && document.getElementById) {
navRoot = document.getElementById("nav");
for (i=0; i<navRoot.childNodes.length; i++) {
node = navRoot.childNodes[i];
if (node.nodeName=="LI") {
node.onmouseover=function() {this.className+=" over"; }
node.onmouseout=function() { this.className=this.className.replace(" over", ""); }
}
}
}
}
window.onload=startList;

As you can see, this code isn’t very neat and fails if “over” is part of another class name. It also overrides any other onload events you have and only runs the code when the page (including images) is fully loaded. The site HTML Dog updated the code to Son of Suckerfish dropdowns:

 sfHover = function() {
var sfEls = document.getElementById("nav").getElementsByTagName("LI");
for (var i=0; i<sfEls.length; i++) {
sfEls[i].onmouseover=function() {
this.className+=" sfhover";
}
sfEls[i].onmouseout=function() {
this.className=this.className.replace(new RegExp(" sfhover\\b"), "");
}
}
}
if (window.attachEvent) window.attachEvent("onload", sfHover);

This is much neater and uses a nice regular expression to remove the class name. It also uses Microsoft’s attachEvent, which is much easier to make non-distructive. There is still a problem with this: the code only executes when the page is fully loaded. What we really need is to wait until the DOM is ready to be manipulated, then run the code. Unfortunately, as we’re aiming this code at IE6, we can’t just do a document.addEventListener(”DOMContentLoaded”, sfHover). The only way we can get a DOM ready event is by creating an empty script with defer=”defer” and listen for it to load, then run our code. This was thought up by Matthias Miller.

The code is now starting to get more complex. We’re also going to be creating functions we’ll probably reuse in the future. Instead of writing our functions from scratch, we’ll use a jQuery, a JavaScript library to do most of the hard work for us.

The jQuery version:

$(function() {
$("#nav li").hover(
function() {$(this).addClass("sfhover)},
function() {$(this).removeClass("sfhover)}
);
};

Fading menus in 5 lines of JavaScript

September 16th, 2008  |  Published in javascript, jquery

Ever wanted your menus to fade when you mouse over them? With jQuery, copy this code into your page and run it when the DOM is ready (That means wrapping it with $(function(){ ... }); to use jQuery’s $(document).ready() function).

Replace #nav li below with whatever your navigation items are.

$("#nav li").hover(function(){ //add an event listener for hover on the li nodes
$(this).fadeOut(0); // fade them to white immediately
},function(){
$(this).fadeIn("slow"); // fade them to their original color our mouse out
});

To extend this, you could use the jQuery animate function, along with the color plug in to just fade the background color and not the text itself.

Making a bookmarklet to swap images with jQuery

May 6th, 2008  |  Published in javascript, jquery

Here’s a rough guide on making a bookmarklet to change the images in a page on hover. This looks for images with “without” in the src and replaces them with “with”. For example, <img src="a-without.jpg"> becomes <img src="a-with.jpg">. This is useful for testing new versions of an image on a page.
First, the jQuery:

jQuery("img[@src*=without]").hover(
  function(){
    withLink=jQuery(this).attr("src").replace('without','with');
    jQuery(this).attr("src",withLink);
  },
  function(){
    withOutLink=jQuery(this).attr("src").replace('with','without');
    jQuery(this).attr("src",withOutLink);
  }
);

Second, wrap it in javascript:(function(){ … })() and remove the
whitespace:

javascript:(function(){jQuery("img[@src*=without]").hover(function()
{withLink=jQuery(this).attr("src").replace('without','with');jQuery(this).attr("src",withLink);},function()
{withOutLink=jQuery(this).attr("src").replace('with','without');jQuery(this).attr("src",withOutLink);})})
()

Save this as a bookmark and click on it on any page with jQuery.

Tags: ,

Welcome to CreateOpen

April 16th, 2008  |  Published in Uncategorized

Hello people.

Here you’ll soon see posts about web development, specifically:

  • Web standards
  • JavaScript
  • CSS
  • PHP