Many sites today use AJAX for a variety of different things but one of the most common is to dynamically change the content on a given page based on user input. There are various different AJAX frameworks out there that can do this...script.aculo.us, jQuery, mooTools just to name a few. I personally prefer jQuery in combination with PHP mostly because of familiarity but to each his own.
The basic concept is simple...
- User provides input usually via interaction with the site such as clicking a link
- The action calls a javascript function that makes an AJAX call to a server side program
- Based on the interaction, our server side program will be responsible for sending content back to the AJAX function.
- The AJAX function executes 'success' code that updates/changes content on the page based on what was returned by the server side program.
<a href="javascript:updateLiveContent('photos');">My Navigation Link</a>
Next, I wrote the Javascript function that was responsible for making the Ajax call using the jQuery framework.
function updateLiveContent(page){
$.ajax({
type:"POST",
url:"updateLiveContent.php",
data:"page=" + page,
cache:false,
dataType:"text",
success: function(data){
$("#content").html(data);
}
});
}
The function makes an ajax call using an $.ajax initializer. The important parts here are
- url - Tells the ajax object which document on the server to request and send data to
- data - The query string to send to the document defined by url
- dataType - The type of data you will be returning from your server side application
- success - The function that will process and update all page content
<?php
$template = $_REQUEST["page"];
$siteUrl = "http://www.mywebsite.com/";
$html = file_get_contents($siteUrl . $template . ".html");
echo $html;
?>
Our PHP file requests the page variable from our ajax call and then gets the contents of an html file based on the siteUrl and template variables. After it has pulled the content in, it simply echos it out right back to the ajax script. Our ajax object then fires its success event which proceeds to change the inner html of a div that has an id of content.
No comments:
Post a Comment