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

WillMaster > LibraryWeb Page and Site Features

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 to Fill Div

This is a tutorial showing how Ajax can be used to fill a div with content obtained from the server. And change the content on demand.

(If you're unfamiliar with Ajax, see Ajax, How It Works and How To Use It.)

Workable content length is anything from an image or short saying to an article thousands of words long. Random content, changing content, content requested by the site visitor – all can be accommodated.

The functionality is based on the JavaScript Ajax engine provided in this article. The JavaScript is copy and paste. No customization required.

Other JavaScript can be created to interact with the Ajax engine JavaScript. But the Ajax code itself is copy and paste.

This tutorial provides some JavaScript to interact with the Ajax engine, enough for the basic functionality of providing:

  1. Random content: You have two or more files on the server. JavaScript determines which to fill the div with and sends the choice to the Ajax engine.

  2. Changing content: You have two or more files on the server. Every so often the content in the div changes. The location of the new content is sent to the Ajax engine.

  3. Content requested by the site visitor: The site visitor clicks on a link to request certain content. The request is sent to the Ajax engine.

But first, here is the copy and paste Ajax engine JavaScript. Paste it into the web page (or import it) with the div that will be filled using the Ajax engine.

<script type="text/javascript">
// Version 1.1 of May 16, 2013
function RequestContent(url,id) {
var http;
if (window.XMLHttpRequest) {
   try { http = new XMLHttpRequest(); }
   catch(e) {}
   } 
else if (window.ActiveXObject) {
   try { http = new ActiveXObject("Msxml2.XMLHTTP"); }
   catch(e) {
      try { http = new ActiveXObject("Microsoft.XMLHTTP"); } 
      catch(e) {}
      }
   }
if(! http) {
   alert('\n\nSorry, unable to open a connection to the server.');
   return false;
   }
http.onreadystatechange = function() { PublishContent(http,id); };
http.open('GET',url,true);
http.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>

Using the Ajax Engine

Besides the Ajax engine JavaScript, three other things are needed on the page:

  1. The div to be filled with content.

  2. Content on the server to use for filling the div.

  3. A way to tell the Ajax engine which content to fill the div with.

The div to fill with content.

The div is an empty div with an id value. It may be styled as you please. The Ajax engine uses the id value to determine which div to fill with the content.

Here is an example:

<div id="fill-me" style="border:1px solid black; padding:20px;"></div>

Put the div on the page where the content is to be seen once the div is filled with the Ajax engine. Nothing else needs to be done with the div.

Content on the server to use for filling the div.

For the Ajax engine to fill the div with content, there must be content on the server for the Ajax engine to obtain.

The content can be any valid HTML content – images, text, forms, videos, and so forth in any combination.

Save the content in files with any valid web page file name – fine names ending with .html or .php, as examples. (Yes, the file may be a PHP script.)

Put the files into a directory on your server that browser's can access. The files need to be accessible with browsers because the Ajax engine uses HTTP to request the files, just like browsers do.

A way to tell the Ajax engine which content to fill the div with.

This section provides the JavaScript for three ways to tell the Ajax engine which content to fill the div with.

The JavaScript requires the location of the files to fill the div with.

About specifying the content location:

Specify the location as a URI (URL relative to document root) instead of an absolute http://... URL.

The reason is because Ajax can't get content from other domains (it sees example.com and www.example.com as different domains), nor can it get content using a protocol different than the web page requesting the content.

That's why the URI is used instead of URL. It ensures both the domain name and the protocol are acceptable because it's the same as the web page running the Ajax engine.

The URI is a location specified as relative to the document root. It is the absolute URL with everything removed up to the first "/" character following the domain name. Thus, these URLs

https://www.example.com/content.php
http://www,example.com/content.php
https://example.com/content.php
http://example.com/content.php

all have the same URI relative to the document root:

/content.php

Three ways to tell the Ajax engine which content to fill the div with:

Here are three ways to tell Ajax which content to request from the server and use it to fill the div. Other ways can be created. These will give you a start.

  1. Random Content —

    The JavaScript to fill the div with random content will run after the page has completed loading.

    The JavaScript selects a URI from a list and sends it to the Ajax engine. The Ajax engine fills the div with the content from the URI.

    Because it is a random selection, the same content may be selected that was previously selected. The more choices, the less likely a selection will be immediately repeated.

    Below is the JavaScript. It needs to know the id value of the div to fill and a comma/space-separated list of URI's to randomly select from.

    <script type="text/javascript">
    // Pick a random URI and send it to the Ajax engine.
    // Version 1.1 of May 16, 2013
    //
    // // // // // // // //
    // Two customizations:
    //
    // Place 1:
    // Specify the id value of the div to fill.
    
    var div_id = "fill-me1";
    
    // Place 2:
    // Between the quotes, all on one line, specify the URI of 
    //   each file to consider as content for the div. Separate 
    //   the URI's with a space, a comma, combination of them.
    
    var URIs = "/library/ajaxcontent1.html, /library/ajaxcontent2.html, /library/ajaxcontent3.html";
    
    //
    // End of customization.
    // // // // // // // //
    
    URIs = URIs.replace(/^[, ]*/,"");
    URIs = URIs.replace(/[, ]*$/,"");
    URIs = URIs.replace(/[, ]+/g,"\n");
    var List = URIs.split("\n");
    var URI = List[ Math.floor( Math.random() * List.length ) ];
    function PublishRandomContent() { RequestContent(URI,div_id); }
    window.onload = PublishRandomContent;
    </script>
    
    

    Put the JavaScript anywhere on the page that JavaScript can run.

    Here is an example of randomly-selected content. The JavaScript has three files to choose from. If you see the same content on reload, do another reload until the content changes.

  2. Changing Content —

    The JavaScript to fill the div with the first of the changing content will run after the page has completed loading. After that, the content will change every number of seconds you specify in the JavaScript.

    Below is the JavaScript. It needs to know the number of seconds between changing the content, the id value of the div to fill, and a comma/space-separated list of URI's to randomly select from.

    <script type="text/javascript">
    // Rotate the content in the URIs list every so many seconds.
    // Version 1.1 of May 16, 2013
    //
    // // // // // // // //
    // Three customizations:
    //
    // Place 1:
    // Specify the number of seconds to wait before the next 
    //   content URI is sent to the Ajax engine to fill the div.
    
    var SecondsToWait = 5;
    
    // Place 2:
    // Specify the id value of the div to fill.
    
    var div_id = "fill-me2";
    
    // Place 3:
    // Between the quotes, all on one line, specify the URI of 
    //   each file to consider as content for the div. Separate 
    //   the URI's with a space, a comma, combination of them.
    
    var URIs = "/library/ajaxcontent1.html, /library/ajaxcontent2.html, /library/ajaxcontent3.html";
    
    //
    // End of customization.
    // // // // // // // //
    
    URIs = URIs.replace(/^[, ]*/,"");
    URIs = URIs.replace(/[, ]*$/,"");
    URIs = URIs.replace(/[, ]+/g,"\n");
    var List = URIs.split("\n");
    var Current = 0;
    var Top = List.length - 1;
    function FillTheDiv()
    {
       RequestContent(List[Current],div_id);
       Current++;
       if( Current > Top ) { Current = 0; }
    }
    function PublishRotatingContent()
    {
       FillTheDiv();
       setInterval("FillTheDiv()",parseInt(SecondsToWait*1000));
    }
    window.onload = PublishRotatingContent;
    </script>
    
    

    Put the JavaScript anywhere on the page that JavaScript can run.

    Here is an example of changing content. Three content files are in the queue. The content changes every 5 seconds.

  3. Content Requested by the Site Visitor —

    The site visitor has links to click for requesting content.

    When the link is clicked, the URI is sent to the Ajax engine. The Ajax engine fills the div with the content from the URI.

    The only JavaScript here is in the links that call the Ajax engine function RequestContent(). Clicking the link fills the div.

    The RequestContent() function in the link has two parameters, both required:

    1. The URI of the content.
    2. The id value of the div to fill.

    Here are example links:

    <ul>
    <li>
    <a href="javascript:RequestContent('/library/ajaxcontent1.html','fill-me3')">
    Click here</a> to fill the div below with the Master Form .PHP logo.
    </li>
    <li>
    <a href="javascript:RequestContent('/library/ajaxcontent2.html','fill-me3')">
    Click here</a> to fill the div below with the Master Form V4 logo.
    </li>
    <li>
    <a href="javascript:RequestContent('/library/ajaxcontent3.html','fill-me3')">
    Click here</a> to fill the div below with the Short URL logo.
    </li>
    </ul>
    
    

    Here is a working example where the site visitor can request content.

    • Click here to fill the div below with the Master Form .PHP logo.
    • Click here to fill the div below with the Master Form V4 logo.
    • Click here to fill the div below with the Short URL logo.

    (The above div will contain the content when one of the "Click here" links are clicked.)

Putting it Together

The above tutorial covers a lot. But there are only four things that need to come together to use Ajax to fill a div.

  1. Put the Ajax engine JavaScript in the source code of the page. It can be put anywhere on the page or it can be imported.

  2. Put an empty div on the page for the Ajax engine to fill.

  3. Put some content files on the server for the Ajax engine to grab to fill the div with.

  4. Tell the Ajax engine which content to grab.

The first three items are fairly standard. Just do them and you're good.

The last item, "telling the Ajax engine which content to grab," varies depending on what you want to do.

The examples show three things that can be done. Others can be created, such as filling the div with different content to repeat visitors than first-time visitors get to see, or with content depending on the country the visitor is from.

Choose one of the ways shown here to test filling a div with Ajax on your server. Then, if your idea of how to use the system requires it, develop your own method of determining which content to use to fill the div.

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