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

WillMaster > LibraryWeb Page and Site Optimization

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 Content From Other Domains

Ajax ordinarily can access only the domain of the web page where Ajax is running. As an example, Ajax at http://example.com/page.html cannot access the http://otherdomain.com/anotherpage.html web page.

But a relay can be provided.

Relay software can request http://otherdomain.com/anotherpage.html and give it to Ajax.

The relay software this article provides is named "Ajax Relay". It has security built in so it can't be used by others to anonymously grab content from any URL on the internet.

Ajax Relay is a PHP script that accepts an internet URL from Ajax, requests the page at the URL, and returns the content to Ajax.

This is perfect for people with two or more domains.

A script or content file at any one of your domains can serve as content for all of your domains. Change the script or file and the content changes across any domains where it's published.

That's the elegance and sheer pleasure of using Ajax this way.

As examples, uses could be the latest bid, the current weather, specially formatted time, the most recent blog post particulars, product specials, and seasonal messages.

Of course, you're not restricted to pulling content only from your own domains. Any domain at any URL with unrestricted, publicly-available content can serve as a content source. (The built-in security lets you limit the URLs to only those you specify.)

The content can be pulled in by clicking a link or during the original page load. Both methods are described in this article.

And one more thing: Ajax runs asynchronously. Thus, when pulled in with the orignal page load, the content Ajax pulls in doesn't slow the page load down. Depending on how much content Ajax does pull in, the original page load can be noticeably faster than if all the content was loaded with PHP or SHTML.

You get two scripts to implement it:

  1. Ajax.

    This is JavaScript to put on your web page or import from an external JavaScript file.

  2. Ajax Relay

    This PHP script is called by Ajax with a URL. The PHP script gets the content at the URL and sends it back to Ajax.

Installation

Let's install the Ajax Relay PHP script first.

The Ajax Relay script —

Here is the script. Customization notes follow.

<?php
/*
   Ajax Relay
   Version 1.0
   September 30, 2017

   Will Bontrager Software LLC
   https://www.willmaster.com/
   Copyright 2017 Will Bontrager Software LLC

   This software is provided "AS IS," without 
   any warranty of any kind, without even any 
   implied warranty such as merchantability 
   or fitness for a particular purpose.
   Will Bontrager Software LLC grants 
   you a royalty free license to use or 
   modify this software provided this 
   notice appears on all copies. 
*/

//*** CUSTOMIZATION ***//
//
// Between the "$URLs=<<<URLSLIST" line and the "URLSLIST;" 
//   line, list the URLs (or the front part of the URLs) that 
//   this script may retrieve content from. List URLs one URL 
//   per line. Blank lines are OK.

$URLs=<<<URLSLIST
http://example.com/testing/
https://example.com/testing/
https://example.com/books/specials.php
URLSLIST;

//
//*** No other customizations required. ***//

$url = urldecode($_SERVER['QUERY_STRING']);
if( ! strlen($url) )
{
   echo('Inappropriate access.');
   exit;
}
$urltest = strtolower($url);
$OKtoProceed = false;
foreach( preg_split('/[\r\n]+/',trim($URLs)) as $u )
{
   $u = strtolower($u);
   if( strpos($urltest,$u) === 0 )
   {
      $OKtoProceed = true;
      break;
   }
}
if( $OKtoProceed ) { echo(file_get_contents($url)); }
else { echo('Inappropriately accessed.'); }
?>

There is only one place to customize. It's where you list the URLs the script may obtain content from.

The customization is a security consideration so not just anyone can use your relay script to anonymously get publicly-available content from other domains.

The entire URLs can be listed or only the front part or the URL. Listing only the front part can come in handy when you will retrieve content at several different URLs of the same domain or subdirectory.

Replace the blue

http://example.com/testing/
https://example.com/testing/
https://example.com/books/specials.php

and list all the URLs your Ajax will need to get content from, one URL per line. (Blank lines are OK.)

Save the file as ajaxrelay.php and upload it to your server. (A different file name may be specified so long as the file name ends with .php)

Make a note of the ajaxrelay.php URL. It will be needed for the Ajax.

The Ajax —

Here is the Ajax JavaScript. Customization note follows.

<script type="text/javascript">
function AjaxRequest(url,div)
{
   var relayScriptURL = "/subdirectory/ajaxrelay.php";
   var http = new XMLHttpRequest();
   if(! http) { return; }
   http.onreadystatechange = function()
   { 
      if(http.readyState==4 && http.status==200) 
      { document.getElementById(div).innerHTML=http.responseText; }
   }
   http.open("GET",relayScriptURL+"?"+url,true);
   http.send();
} // function AjaxRequest()
</script>

Customization: Replace /subdirectory/ajaxrelay.php with the relative URL of ajaxrelay.php on your server. (The relative URL is the absolute URL with http:// or https:// and the domain name removed.)

Put the Ajax JavaScript somewhere on the web page where it will be used. Near the bottom of the page above the cancel </body> tag is good. Alternatively, the Ajax JavaScript may be pulled into the page from an external file.

The system is now installed and ready to use.

Using Ajax With the Ajax Relay Script

To use the system, two things are needed: A div (or other HTML container) to put the Ajax content into and a call to Ajax to get the content.

Here's an example div.

<div id="DIV-ID"></div>

Two ways to call Ajax with a URL are provided here.

Automatic content load —

Use JavaScript like this to put the content of http://example.com/page.html into the div with id="DIV-ID". Because the JavaScript may run as soon as the browser receives it, this JavaScript needs to be somewhere below both the div with the id="DIV-ID" attribute and the Ajax JavaScript.

<script type="text/javascript">
AjaxRequest("http://example.com/page.html","DIV-ID");
</script>

Customizations:

  1. Replace http://example.com/page.html with the URL of the content to retrieve.

  2. Replace DIV-ID with the id value of the div or other HTML element where the retrieved content is to be put.

Click to load the content —

Use a link like this to put the content of http://example.com/page.html into the div with id="DIV-ID" when the link is clicked. The link can be anywhere on the page.

<a 
   href="javascript:AjaxRequest('http://example.com/page.html','DIV-ID'">
   Click here.
</a>

The customization is identical to the customization for the automatic content load. They're repeated here for convenience.

  1. Replace http://example.com/page.html with the URL of the content to retrieve.

  2. Replace DIV-ID with the id value of the div or other HTML element where the retrieved content is to be put.

Multiple Ajax calls for various URLs —

As many div and AjaxRequest calls as needed may be put on a page. They may be automatic content load and/or click to load. Each additional instance needs an additional div/AjaxRequest set.

  1. Place the additional div where you want the retrieved content to be. The id value DIV-ID needs to be changed so the value is unique on the page. Duplicate id values may have unexpected results.

  2. Somewhere below the additional div, place the additional JavaScript with the AjaxRequest function call. The function call parameter data is the URL of the content to retrieve and the id value of the additional div.

Regardless how many Ajax calls you make on any one or more web pages, the domain needs only one Ajax Relay installation.

Consider this system when you have identical content to be inserted into two or more domains — or when you need to retrive content from another domain to insert into your page without slowing down the original page load.

(This article first appeared in Possibilities newsletter.)

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