Very Simple Easy AJAX Example!

How many times have tutorials said that! Well, i'll try and make this as simple as possible.

Example:

Load Some Information
 

Introduction

Ajax is a way of loading content into a page without reloading the whole page. It makes things quick, and allows more interactive page and give you many more options for user interface designs

The sequence of events (in this example)

  1. User click on the link
  2. This calls (runs) a javascript function
  3. This javascript function opens up another html page, and reads the content of the page
  4. The javascript puts all that content into the main page we are on now

Step 1. Creating the javascript function

First we have to create the javascript function, this can be anywhere on your HTML course, but it usual in the between <head> </head> sections to keep your page itself clear of code

Javascript Human Person Language

<script type="text/javascript">

 

var http = false;

 

if(navigator.appName == "Microsoft Internet Explorer") {

http = new ActiveXObject("Microsoft.XMLHTTP");

} else {

http = new XMLHttpRequest();

}


function loadInformation(textBoxInput) {

http.abort();

 

http.open("GET", "newpage.html", true);


http.onreadystatechange=function() {
if(http.readyState == 4) {
document.getElementById('loadArea').innerHTML = http.responseText;
}

}

 

}

http.send(null);

}

</script>

Tell the browser that this part is javascript code

 

This part does some fancy stuff, don't worry what it means, it just sets up the javascript stuff so it can go and get information from another page

 

 

 

 

 

Start a function called loadInformation

 

 

This is the important bit! It opens up the page 'newpage.html'

 

This part waits until javascript has opened up the page

 

And sets the content of a div called 'feedback' to the content of the PHP page

Step 2. Making the link run the function!

HTML Text Input Form Field Human Person Language

<a href="#" onclick="loadInformation(); return false">Load Some Information</a>

This is just a simple link. The 'onclick=loadInformation()' bit means that, when some clicks on the link, it runs the javascript function called loadInformation.

 

The 'return false' bit just stops the page scrolling to top every time you click on the link

Step 3. The HTML page to load in.

HTML Page

On this html page, you can put what ever you want!

Save this file as newpage.html.

Try it, it should all work!