thedigitalfeed.co.uk content

thedigitalfeed.co.uk/Code

AJAX: Nice and Easy

Posted on Tuesday the 24th of January, 2006

www.thedigitalfeed.co.uk/code/2006/01/24/ajax-nice-and-easy



Finally, we'll need a function to take data from the server response, parse it and inject it back in to the page. I haven't abstracted this much either, since it's only used for one thing and I don't think I'll be expanding it:

function updatePage() {
// get the content from the server and update the page.
if (request.readyState == 4) {
if (request.status == 200) {
var response = request.responseText.split("|||||");
document.getElementById('help_name').innerHTML=response[0];
document.getElementById('help_data').innerHTML=response[1];
}
}
}


The server sends back a string with two values – title and content, separated by an arbitrary string ('|||||'). We then split the response using this separator, and use Javascript to replace the innerHTML of the designated <div> tags on the page.

That wraps it up for the AJAX functions. Triggering these functions is really up to you. On my page, each page element has a title, so when PHP outputs these to a page, I changed each element title to an <a> tag with an OnClick event:

<a OnClick=”getData('name','page_content')”>Page Content</a>


These links are generated automatically by PHP. When the link is clicked, getData() will run and trigger the script on the server. When a response is received, the Javascript will plit the string up and insert the relevant parts into the page.

Page: