Software, your way.
How To Get Good Custom Software
(Download)
(PDF)
burger menu icon
WillMaster

WillMaster > LibraryWebsite Development and Maintenance

FREE! Coding tips, tricks, and treasures.

Possibilities weekly ezine

Get the weekly email website developers read:

 

Your email address

name@example.com
YES! Send Possibilities every week!

Ajax, How It Works and How To Use It

Ajax is written with JavaScript using specialized functions with the ability to connect to the server.

The code that connects to the server and accepts its response is sometimes referred to as an Ajax engine.

An Ajax engine is provided with a URL and, optionally, data to send to the server. The engine then proceeds to make the connection to the server and listens for the server's response. When the response is received, the Ajax engine relays the information to whatever JavaScript function will handle it.

Generally, the server's response is inserted into a div on the page. The response may be edited or conformed for display before it is inserted.

An Ajax engine can connect only to the server of the web page's domain. In other words, a web page with an Ajax engine at URL http://example.com/ can connect only with files on example.com. It's a security feature.

How It Works - By Example

This web page has JavaScript with an Ajax engine. The Ajax will connect only with scripts and files on the www.willmaster.com domain.

When [this link] is clicked, the current date and time on the server is displayed immediately below this line.

Here is what happened when you clicked the link.

  1. JavaScript in the link gave the Ajax engine the URL of software on the server. (The software provides the current date and time according to the server's clock.)

  2. The Ajax engine connected with the server with a request for a response from the software.

  3. The software responded.

  4. The server gave the software's response to the Ajax engine.

  5. The Ajax engine relayed the response to the JavaScript function that inserts the response into the the web page.

How To Implement the Example

Four things are required to implement the above example.

  1. Software for the server.
  2. JavaScript for the web page.
  3. A link to click for the web page.
  4. A div for the web page where the date and time are inserted.

The code for the example is below. All is copy and paste, no edits needed.

  1. The Software.

    The software consists of the 5 lines of code in the text box below. Copy the code and save it as a PHP web page named TestingAjax.php

    Upload TestingAjax.php to your server into the document root directory. The document root directory is the where your domain's main or index file is at.

    <?php
    echo date('l, F j, Y');
    echo ' at ';
    echo date('H:i:s')
    ?>
    
    
  2. The JavaScript.

    Put the JavaScript on a web page anywhere that JavaScript can run, in the HEAD or BODY area.

    <script type="text/javascript" language="javascript">
    function GetContent(url,id) {
    var httpRequest;
    if (window.XMLHttpRequest) {
       try { httpRequest = new XMLHttpRequest(); }
       catch(e) {}
       } 
    else if (window.ActiveXObject) {
       try { httpRequest = new ActiveXObject("Msxml2.XMLHTTP"); }
       catch(e) {
          try { httpRequest = new ActiveXObject("Microsoft.XMLHTTP"); } 
          catch(e) {}
          }
       }
    if(! httpRequest) {
       alert('\n\nSorry, unable to open a connection to the server.');
       return false;
       }
    httpRequest.onreadystatechange = function() { PublishContent(httpRequest,id); };
    httpRequest.open('GET',url,true);
    httpRequest.send('');
    }
    
    function PublishContent(content,id) {
    try {
       if (content.readyState == 4) {
          if(content.status == 200) { document.getElementById(id).innerHTML=content.responseText; }
          else { alert('\n\nContent request error, status code:\n'+content.status+' '+content.statusText); }
          }
       }
    catch(error) { alert('Error: '+error.name+' -- '+error.message); }
    }
    </script>
    
    
  3. The Link.

    Put the link on the web page.

    <p>
    <a href="javascript:GetContent('/TestingAjax.php','exampledatetime')">
    [click this link]
    </a>
    </p>
    
    
  4. The Div.

    Put the div on the web page.

    <div id="exampledatetime"></div>
    
    

When the above steps are done, upload the web page with the JavaScript and link to your server. Then type its URL into your browser.

When the link is clicked, the server's date and time will in the div.

How To Use Ajax

The Ajax engine JavaScript in the date and time example above can be used for any URL on your server except software that requires method POST. (Method POST Ajax engines can be created. The Ajax in this article uses method GET.)

It's a copy and paste Ajax engine. No modifications needed.

An Easy Implementation:

Let's implement something simple.

Put the Ajax engine JavaScript, the link, and the div from the above date and time example into a web page. In the link, change the '/TestingAjax.php' URL to '/' (the URL to your domain's default index page).

Upload the page to your server and type it's URL into your browser. When you click on the link, the content of your index page will load into the div.

Implementing Ajax:

To implement Ajax, put the Ajax engine JavaScript, the link, and the div into a web page. Change the URL in the link to the URL of the web page or software you want to connect to.

That's the gist of it.

When the link is clicked, the Ajax engine is started. It connects to the server and publishes the response in the div.

The Ajax engine can be started with something other than a link click. With a mouse move, when the page has completed loading, or after a certain amount of time has elapsed, are examples. The link for the above date and time example might be replaced with a mouseover, like this:

<p onmouseover="GetContent('/TestingAjax.php','exampledatetime')">
[hover mouse here]
</p>

The response can be inserted into something other than a div. Any HTML content container will do. That may be div, span, td, pre, or other tag. The above date and time example might be put into a span tag, like this:

<p>
The current server date and time is 
<b><span id="exampledatetime"></span></b>
</p>

It is not necessary to display the server response. Simply give the div where the content will be published a CSS style="display:none;"

Another Implementation:

JavaScript by itself can not create or update files on a server. With Ajax, JavaScript can connect with software on the server and the server software may create and update files.

This Perl CGI script will log the visitor's IP address. The Ajax engine will connect to the software when the page loads.

#!/usr/bin/perl
# Specify location of log file. Directory must exist and have proper permissions.

my $LogFileLocation = "log/log.txt";

use strict;
open W,">>$LogFileLocation";
print W "$ENV{REMOTE_ADDR}\n";
close W;
print "Content-type:text/plain\n\nDone";
# end of script

Use a plain text processor like NotePad or TextWrangler and save the above to a file named LoggerForAjax.cgi

Upload it to your server in a location that can run Perl CGI scripts. Upload with FTP as plain text, not as a binary file. When uploaded, give the script 755 permissions.

Make a note of the script's URL.

In the directory where script is installed, create a subdirectory named "log". Give the subdirectory 755 permissions. (Some servers may require 766 or 777 permissions.)

The software is installed. Verify it runs without errors by typing its URL into your browser.

Now, let's prepare the web page.

  1. Put the Ajax engine JavaScript into the web page.

  2. Put an automatic Ajax engine starter on the web page. It can be put anywhere in the BODY area of the web page below the Ajax engine JavaScript.

    <script type="text/javascript">
    GetContent('/cgi-bin/LoggerForAjax.cgi','logger');
    </script>
    
    

    Change the URL in the automatic Ajax engine starter to the URL of the newly-installed software.

    Because it is Ajax, the page loading will not pause while the logging script is contacted. It works silently behind the scenes without interrupting.

  3. Put the div into the web page. Give the div a style="display:none;" attribute so the software's response won't be displayed on the page.

    <div id="logger" style="display:none;"></div>
    
    

Upload the web page to your server and type its URL into your browser. Your IP address is then recorded in the log file.

Potential:

Ajax can be used to retrieve the content at any URL. The Ajax provided with this article uses method GET. Method POST Ajax can be created.

The server's response is generally published on the web page. But it is not necessary to publish the response, the entire process can be silent, unnoticed.

Will Bontrager

Was this article helpful to you?
(anonymous form)

Support This Website

Some of our support is from people like you who see the value of all that's offered for FREE at this website.

"Yes, let me contribute."

Amount (USD):

Tap to Choose
Contribution
Method

All information in WillMaster Library articles is presented AS-IS.

We only suggest and recommend what we believe is of value. As remuneration for the time and research involved to provide quality links, we generally use affiliate links when we can. Whenever we link to something not our own, you should assume they are affiliate links or that we benefit in some way.

How Can We Help You? balloons
How Can We Help You?
bullet Custom Programming
bullet Ready-Made Software
bullet Technical Support
bullet Possibilities Newsletter
bullet Website "How-To" Info
bullet Useful Information List

© 1998-2001 William and Mari Bontrager
© 2001-2011 Bontrager Connection, LLC
© 2011-2024 Will Bontrager Software LLC