Ajax

From virtualMV2015wiki
Jump to: navigation, search
 Home  JavaScript, Main Page <

Introduction

Overview

AJAX ( Asynchronous JavaScript and XML) is a combination of internet technologies that allow you to refresh partial web pages in real time, and include: HTTP Requests and Responses( especially XMLHTTPRequest), DHTML and XHTML, CSS, JavaScript, Server-side Programming (e.g. PHP, ASP ASPX) and XML and XSLT. This allows a browser to retrieve an area of the currently displayed web page (such as updates from Facebook or Twitter) without sending a request for the entire page.

The following example is a summary of a discussion by Welling and Thomson (2009, p.855-869)[1] and gives an example of an AJAX application that retrieves the server system date and time when you roll over a designated area on the web page.

Resources

From Adriel K. Oct 28, 2008.


Icon Objectives.png

Objectives

By the end of this page you will be able to:

  • Describe the fundamentals of AJAX.
  • Describe the Internet technologies involved in implementing an AJAX Solution
  • Use the examples shown to create a sample AJAX application.

HTTP Request and Response

Hypertext Transfer Protocol (HTTP) is an Internet standard way that allows the web client (Browser) to communicate to the Web Server.

  • A user types in a URL and the Browser sends an HTTP request, for example:
Line 
1GET http://server/ajaxexample.html HTTP/1.1
..Optional header lines
.Blank line
..Optional message body
  • where
    • For line 1: method (GET) path (http://server/AjaxExample.html) HTTP Version (HTTP/1.1)

After processing the request the Server will send a response, for example:

Line 
1HTTP/1.1 200 OK
..Optional header lines
  • Where:
    • the 200 is the status code: 1##=information, 2## = success, 3## = redirection, 4## = error (e.g. 404 error), 5## = malformed scripts

This handles the overall page request/response cycle, but now we need to request only part of the page from the server. To do this we need to create an XMLHTTPRequest object, this requires JavaScript

JavaScript

JavaScript is a client side programming language that can be inserted into an HTML Web page. Using JavaScript we will

  1. create the XMLHTTPRequest JavaScript Object
  2. call the function that creates (instantiates) the XMLHTTPRequest JavaScript Object
  3. create a function that uses the XMLHTTPRequest Object to ask the server for the date and time

XMLHTTPRequest JavaScript Object

It is best to link the html page to a separate js file. So in the html page header you will need to include
<script src="AjaxFunctions.js" type="Text/javascript"></script>


and create the following AjaxFunctions.js text file .

function fnGetXMLHTTPRequest() {
   var req =  false;
   try { req = new XMLHttpRequest(); }// for Firefox 
   catch (err) {
      try { req = new ActiveXObject("Msxml2.XMLHTTP"); }//some versions of IE
      catch (err) {
         try { req = new ActiveXObject("Microsoft.XMLHTTP");} //other versions of IE
         catch (err) { req = false; }
      }
    }
    return req;
}
  • Notes:
    • This code is required to handle the inconsistencies of different web browsers :(
    • the XMLHTTPRequest object can only call URLs in the same domain as the original web page.

Create (instantiate) XMLHTTPRequest Object

Then in the html page add

<head>
...
<script src="AjaxFunctions.js" type="Text/javascript"></script>
<script type="text/javascript">
// put fnGetServerInfo() code here (following)---
// put fnHTTPResponse() code here (following)--
 
var objRequest = fnGetXMLHTTPRequest();
</script>
</head> 
...

Request date/time from the server

Now we need some code to request the date/time from the server. So we use a JavaScript function that we will call in the html file. Add the following code into the html file (JavaScript area) as indicated previously.

function fnGetServerInfo() {
  var strPage = 'AjaxExample.php';
  var strURL = strPage +"?rand="+parseInt(Math.random()*999999999999999);
  objRequest.open("GET", strURL, true);
  objRequest.onreadystatechange = fnHTTPResponse;
  objRequest.send(null);
}
  • Notes
    • The random number in the URL is to make sure the retrieved data does not come out of the browsers cache.

Server Side Script (PHP)

Now we need to create a script that is run by the server that will return the date and time. This can be done in any server programming language, however here I will use php.

Create a php file on the server in folder ajax called AjaxExample.php

<?php
header('Content-Type: text/xml');
echo "<?xml version=\"1.0\" ?>
      <serverinfo>
        <info>On the Server it is ".date('H:i:s')." on ".date('M d, Y').".</info>
      </serverinfo>";
?>

XML

The XMLHTTPRequest Object needs to receive a correctly constructed XML file (XML files follow very strict formatting rules). So, the php code will create an XML file, that will look like (The server will put in the correct current date and time):

<?xml version="1.0" ?>
<serverinfo>
   <info>It is 12:23:30 on Oct 04, 2009</info>
</serverinfo>";

So we now need to interpret the response sent by the server. We need to create the function fnHTTPResponse (called in function fnGetServerInfo).

function fnHTTPResponse() {
  if (objRequest.readyState == 4) {
    if(objRequest.status == 200) {
       var strInfo = objRequest.responseXML.getElementsByTagName("info")[0];
       document.getElementById('ShowInfo').innerHTML = strInfo.childNodes[0].nodeValue;
    }
  } else {
    document.getElementById('ShowInfo').innerHTML = '<img src="AjaxLoad.gif"/>';
  }
}
  • Where
    • AjaxLoad.gif is an animated image showing that the request is being processed by the server.

Dynamic HTML (DHTML)

Dynamic HTML is actually a combination of static HTML, Cascading Style Sheets and JavaScript to work with the Document Object Model (DOM) (Whew!!). The DOM can be thought of as a tree diagram constructed from the tags in an HTML page. So a simple DOM for a web page is:

<html>
|-<head>
|  |-<title>
|-<body> 
   |-<h1>
   |-<p>

We access the contents of each node by using the getElementById command and change the contents on the web page by accessing the innerHTML attribute (this is seen in the JavaScript code shown previously).

However, its not quite all there, as we have not told the Browser when to update the server date and time. So we need to do two things,

  1. create an area for the web page to display the contents and
  2. tell the browser to send a request to the server when something happens (in this case when the mouse is rolled-over the area).

Cascading Style sheet

CSS allows us to format the display of the html independent of the html tag. In this case I will use the CSS to create a style for the box that will display the server information. The following style is added into the HTML file.

<style>
<style>
.displaybox {
       width: 300px; height: 50px; border: 1px solid #808080;
       margin-right:auto;margin-left:auto; background-color: #F6F9ED;
       font-weight:bold; cursor: pointer;}
</style>
  • Note
    • the cursor setting turns the mouse pointer into a hand.

Javascript

and for the last piece of the puzzle I need to add a mouseover JavaScript onto the information display area.

<body>
<div style ="text-align:center;">
   <h1>Ajax Demonstration 1</h1>
   <p>move you mouse over the box to show the server information <br />
	 (only the box will be refreshed!)</p>
   <div id="ShowInfo" class="displaybox" onmouseover="javascript:fnGetServerInfo();"></div>
</div>
</body>

.. and thats all there is to it. If you want to get a more through discussion please read Welling and Thomson (2009, p.855-869)[1].

Examples

Icon Example.png

Example

  • Show what is returned by the server

AjaxExample.php

  • Show the AJAX working

AjaxExample.html

Icon References.png References

  1. 1.0 1.1 Welling, L., & Thomson, L. (2009). PHP and MySQL Web Development. (4th Ed.) Developer's Library. Addison-Wesley. ISBN 978-0-672-32916-6

Ajax. (2017). In virtualMV's ( Michael Verhaart ) wiki. Retrieved May 23, 2017, from http://www.virtualmv.com/wiki/index.php?title=Ajax    (zotero)