This course will become read-only in the near future. Tell us at community.p2pu.org if that is a problem.

Sample Code for Learning [Aug. 17, 2011, 12:59 a.m.]


For anyone that has some tested code that would work as a good example to practice with, please drop it here. Anyone that has a better idea for posting working samples of code, please feel free to drop your thoughts here.

If there's a link to examples, post that as well!

Babysteps To an AJAX REQUEST
the following example uses an initial page of index.html and sends a request to another page titled whatever you'd like. Feel free to replace our example of 'request.html' with your page name

<!doctype html>
<html>
<head>
<meta charset="UTF-8" />
<title>Ajax Application</title>
</head>

<body>
 
<span id="ajaxButton" style="cursor: pointer; text-decoration: underline">
  Make a request
</span>
 
<script>
(function() {
 //create instance of http request
  var httpRequest;
  
  //create the trigger for the response
  document.getElementById("ajaxButton").onclick = function() { makeRequest('request.html'); };
 
   function makeRequest(url) {
    //create a cross-browser instance(i.e. object) of the required class
  if (window.XMLHttpRequest) { // Mozilla, Safari, ...
      httpRequest = new XMLHttpRequest();
    } else if (window.ActiveXObject) { // if IE
    try {httpRequest = new ActiveXObject("Msxml2.XMLHTTP");}
    catch (e) {
        try { httpRequest = new ActiveXObject("Microsoft.XMLHTTP");} 
        catch (e) {}//end catch (e)
      }//end catch (e)
}//end elseif
 
    if (!httpRequest) {
      alert('Giving up :( Cannot create an XMLHTTP instance');
      return false;
}//end if !http request
    
    //process the server response
    httpRequest.onreadystatechange = alertContents;
    //make the formal request and set the parameters
    httpRequest.open('GET', url);
    httpRequest.send();
    
  }//end makeRequest(url) function
 
  function alertContents() {
    if (httpRequest.readyState === 4) {
      if (httpRequest.status === 200) {
        alert(httpRequest.responseText);
    }else {
      alert('There was a problem with the request.');
    }//end else
  }//end initial if
}//end alertContents() function
} //closing bracket
)();//end function
</script>
</body>
</html>