Emulating ServerXmlHttpRequest with XmlHttpRequest in JavaScript

System Requirements:

  • A web browser
  • JavaScript

The Problem:

So you want to use ServerXmlHttpRequest in JavaScript? Well, let me spoil your afternoon for you. You can’t. However that are a few things that – if you are desperate enough – might be able to help you overcome the problem.

This document offers a high level overview of my thinking on the problem.

More Info

XmlHttp is an extremely power tool. As a coding apparatus, it has brought about Asymmetric JavaScript And Xml (AJAX) which has redefined the web user interface paradigm. Yet Microsoft also created something else, something very similar, but a little bit different, the ServerXmlHttp object.
There are several key differences between the two:

XmlHttp ServerXmlHttp
Intended use Client -> Server Server -> Server
Server -> Client
Concurrent Connection Limit (per-domain, session*) Depends upon the browser
2 in legacy IE, raised to 6 in IE 9 or higher?++
None (RAM and socket availability are practical limits however)
5460 in MS XML 3.0
Concurrent Connection Limit (session*) 17++ None (RAM and socket availability are practical limits however)
5460 in MS XML 3.0
Works in JavaScript Yes No
Works in JScript Yes Yes
Works in VBScript Yes Yes (ASP / IE)
Works in COM Yes Yes
Supports Sessions Yes No
Supports Cookies Yes No
Supports Http Proxy discovery Yes No (use proxycfg.exe)
Supports Authentication Yes No
URL Caching Yes No
HTTP/1.1 Chunking Yes No
Works in ‘Offline’ mode Yes No
Supports Gopher Yes No
Supports FTP Yes No
Provider URLMon/WinInet WinHTTP
Availability MS XML 2.0 or higher
MS IE 5.0 or higher
MS XML 3.0 or higher
MS IE 5.01 or higher

* This number reflects the entire session. If you are loading in a web browser, this includes the page, each image loading concurrently on the page, all scripts being pulled in. Once they are all loaded (or timeout), XmlHttp can have access to the full number, but not before.
++ You can use browserscope to assess the connection limits for different browser versions
http://www.browserscope.org/?category=network&v=top

Why would you ever need to do this?

The reason is specifically related to performing tasks that take a very long time to complete without encountering a blocking I/O state on the web browser. In 2017, that means JavaScript and simply put, you cannot use ServerXmlHttpRequest in JavaScript and make your web application browser independent.

If you need to ask a server to calculate PI to 1,000,000 digits and then for scientific reasons need it to verify that 9 more times, get the results and compare the answers – and you want to do it asynchronously. You cannot do this with XmlHttp (especially if you don’t want your web browser to appear to crash to the end use).

If you want to have the browser appear to still be responsive while it waits for the 10 answers to come back, you need to find a different solution.

So what can you do if you require more connections than the client allows?

You are fairly limited here in what you can do as this is an intended design of XmlHttp and not a limitation – it is a good one too otherwise there would be a considerable security impact (DDOS) as well as performance implications for things such as battery life, CPU usage caps and the negative effects of JavaScript on the browsing public.

Make it IE only

Hard code your solution so that it only works in IE and make any necessary client changes to the IE configuration to make it work correctly.

Obviously, this isn’t a serious solution.

Modify the registry/browser configuration to increase the concurrent limit count

Again, obviously, this isn’t a serious solution.

Use multiple domains/sub-domains

Reduce the number of elements loading on the page from the same source (having a separate domain/sub-domain for images and include files is often stated as an aid here).

Use additional server side worker processes to implement

After some trial and error, I realised that the connection limits are in practice imposed against the HTTP connection session on a per-port basis. If you create multiple IIS work processes to receive and process requests from the same client, you can increase considerably the number of connections made to the same domain from a single client. But it does consume more server resources and it does require some “thread pool” (I use the term lightly) management logic be added to the client.

How do you do that? Bindings. For each additional socket and binding that you create (using the same domain name) you can double the number of concurrent per-domain connections. For example

Let’s connect to the non-existent web address http://www.myajaxdomain.com/ajax-api/calculatePi/1000000

That is actually shorthand for http://www.myajaxdomain.com:80/ajax-api/calculatePi/1000000.

If in IIS you add additional port binding for the EXACT SAME website and domain name for Port 81, 82, 83, 84 and 85 you will have added significantly more concurrent connections to the potential pool.

In this example, you can treat the port 80 instance as the reserved for the client (if a user clicks away in the browser, the page will respond immediately because all other traffic is dead-locked on 81, 82, 83, 84 or 85.

With the socket connections to 81-85 you create a pseudo-thread pool and allocate workers in the client to each of the pool entries. You then need to register the correct call back function in JavaScript to allocate and deallocate each “thread” on the client.

Your web browser can now wait for the 10 results to come back, sending the next request as a new “thread” becomes available on the server.

Example “thread pool” call to /ajax-api/calculatePi/1000000

http://www.myajaxdomain.com:80 Reserved
http://www.myajaxdomain.com:81 Available = False
XmlHttpStatus = 3
Callback = myCallbackFunction()
http://www.myajaxdomain.com:82 Available = False
XmlHttpStatus = 1
Callback = myCallbackFunction()
http://www.myajaxdomain.com:83 Available = True
XmlHttpStatus = null
Callback = null
http://www.myajaxdomain.com:84 Available = True
XmlHttpStatus = null
Callback = null
http://www.myajaxdomain.com:85 Available = True
XmlHttpStatus = null
Callback = null

You will need to implement CORS headers in order to use this workaround successfully, however it does work although you will NOT be able to share Session information between each socket connection (unless you implement session awareness / sharing in your application layer).

I am going to compare this idea (which I have used in anger and has saved me after much thought and days of time trying to find a solution) to that of creating a thread pool. It is in effect a logical creation of a client side thread-pool. It requires a lot of work in the client code to create and manage the “threads” and it needs a lot of checking to ensure that you do not wind up dead-locking your browser session. Consequently, this approach is not for the faint hearted.

That said, it keeps the entire code base client side and relieves pressures on the creation of state awareness and the server side session management subsystem. It also reduces the risk to your IIS application because you are (or can) use additional IIS worker processes in isolation. You can even create multiple IIS website whose bindings are completely isolated from each other and share the code base.

The disadvantage is that clients will need to have firewall access to each of the new socket addresses that you create, which can be a problem for a publicly accessible web application.

Implement a Server Side Queue

The final way that you can overcome the limitation is to create a traceable queue and perform all of the operations in the server session process. This basically moves the creation of the “thread pool” from the client, onto the server, allowing the server to process the logic using ServerXmlHttpRequest, bypassing any limits.

This would look something akin to the following:

  1. Client contacts web services and requests the function for calculating Pi to 1000000 places 10 times http://www.myajaxdomain.com/ajax-api/calculatePi/1000000/10.
  2. Server creates a worker pool with 10 slots in the session, generates a unique transaction ID (abz678), starts them running (this is where the black magic needs to occur in your solution) and sends the transaction ID back to the client
  3. The client disconnects
  4. Every n seconds the client contacts the server, this time sending with it the transaction ID and the entry that it wants the result for http://www.myajaxdomain.com/ajax-api/getPiCalulationResult/abz678/5. The server looks up the results and returns the status to the client e.g.
    {
    Transaction: ‘abz678’,
    Index: 5,
    Status: ‘Complete’,
    Result: ‘3.14159265359…………’
    }or{
    Transaction: ‘abz678’,
    Index: 5,
    Status: ‘Processing’,
    Result: null
    }

    or

    {
    Transaction: ‘abz678’,
    Index: 5,
    Status: ‘Failed,
    Result: ‘Error -123456 occurred’
    }

  5. Once the client has received a Complete/Failed return for each of the 10 iterations, it will terminate activity and it will be up to you and the server how it cleans-up.

This is the most complicated method to implement. You still have all of the “pool” headaches to contents with, just in a different place. Additionally, you have to persist processing state in your web application and you need to ensure that the server is processing everything wholly asynchronously, something that may actually require additional code to be present on the web server to provide CRON/scheduler service support, or a fully blown queue pick-up service to be available.

You also need to convert your system into what is effectively a message passing system which isn’t an easy task to perform if you are maintaining or converting a system.

The advantage of this approach is that it is the best way to undertake the task. The disadvantage however is that you can quickly get into an infinite spiral of abstraction that ultimately pushes the point where the work is performed in your programme to increasingly lower levels.

At that point, you’ve probably forgotten you were trying to calculate Pi in the first place.

Simple Fourm YouTube API Video Embed Sample Script

System Requirements:

  • HTML

The Problem:

www.hpcfactor.com’s forum software dates from 2004. At some point in the interim I rigged it to support a basic

BBS markup tag which uses a <embed> tag and the legacy a Flash object to inject a video from YouTube onto the page:

<object width="640" height="390">
 <param name="movie" value="{param}"></param>
 <param name="allowFullScreen" value="true"></param>
 <param name="allowScriptAccess" value="always"></param>
 <embed src="{param}" type="application/x-shockwave-flash" allowfullscreen="true" allowScriptAccess="always" width="640" height="390"></embed>
</object>

It is however currently 2016 and HTML 5 is the norm now, so at the behest of a user I wanted to update it.

More Info

Using the formal YouTube APU Reference for iframe Embeds sample. I needed to make something quick and easy that could be injected into the (extremely limited) BBS Markup system on the 12 year old hpcfactor.com forum. The only default substitution available without re-writing the forum core is {param} which takes the <URL> value from the BBS

markup.

View: YouTube Player API Reference for iframe embeds

 

The code sample shown below was the quickly generated solution. The steps it goes through are:

  1. Drop a DIV in-line on the page for the YouTube API to replace with the iFrame
  2. Drop the JavaScript in-line as well (it has some unnecessary duplication but won’t execute)
  3. The JavaScript checks to see if the YouTube API is already on the stack, if it is not it loads the YouTube API, if it is, it skips to the call to the JavaScript to embed the iFrame
  4. If the youTube API is not loaded, it loads the youTube API, sets up an array structure to act as a callback and pointer reference source to track all video files requested to be embedded on the page
  5. It sets up the onYouTubePlayerAPIReady listener to listen for the ‘ready’ callback from the youTube API, at which point JavaScript will be told to parse the sources array and create the iFrame’s
  6. A registration function is provided. This receives video registrations even before the YouTube API is ready. As soon as the YouTube API callback to the onYouTubePlayerAPIReady listener, the video registrations are processed. Until it does, they queue.
  7. A function to test to see if the video has already been embedded is provided and is flagged once it has been embedded

<div id="videoPlayer_{param}"></div>
<script type="text/javascript">
// Load the IFrame Player API code asynchronously.
if (document.getElementById('youTubeExternal') === null) {
var tag = document.createElement('script');
tag.id = 'youTubeExternal';
tag.type = 'text/javascript';
tag.src = "https://www.youtube.com/player_api";
var headTag = document.getElementsByTagName('head')[0];
headTag.appendChild(tag);
var arrVideoStack = new Array();
arrVideoStack[0] = new Array(); // 0 = player reference, 1 = Display Elm ID, 2 = Video ID, 3 = IsLoaded
arrVideoStack[1] = new Array();
arrVideoStack[2] = new Array();
arrVideoStack[3] = new Array();
var iVideoCount = 0;
var bolYtReady = false;// Replace the 'ytplayer' element with an <iframe> and
// YouTube player after the API code downloads.
function onYouTubePlayerAPIReady() {
bolYtReady = true;
loadVideos();
}function registerNewVideo(strTargetElmId, strVideoId) {
strVideoId = strVideoId.replace('https://www.youtube.com/watch?v=', '');
strVideoId = strVideoId.replace('https://www.youtube.com/v/', '');
strVideoId = strVideoId.split('&')[0]; // In case there are any more parameters
arrVideoStack[0][iVideoCount] = null;
arrVideoStack[1][iVideoCount] = strTargetElmId;
arrVideoStack[2][iVideoCount] = strVideoId;
arrVideoStack[3][iVideoCount] = false; iVideoCount++;
if (bolYtReady) {
loadVideos();
}
}function loadVideos() {
if (bolYtReady) {
if (iVideoCount > 0) {
for (i = 0; i < iVideoCount; i++) {
// If it hasn't already loaded, load it
if (!arrVideoStack[3][i]) {
arrVideoStack[0][i] = new YT.Player(arrVideoStack[1][i], {
height: '640',
width: '390',
videoId: arrVideoStack[2][i]
});
arrVideoStack[3][i] = true;
}
}
}
}
}
}

registerNewVideo('videoPlayer_{param}', '{param}');
</script>

If you would like to test it without the BBS markup parts in-situ you can copy and paste the following version into a .html file and double click on it

<div id="videoPlayer_Test1"></div>

<div id="videoPlayer_Test2"></div>

<div id="videoPlayer_Test3"></div><script type="text/javascript">

// Load the IFrame Player API code asynchronously.

if (document.getElementById('youTubeExternal') === null) {

var tag = document.createElement('script');

tag.id = 'youTubeExternal';

tag.type = 'text/javascript';

tag.src = "https://www.youtube.com/player_api";

var headTag = document.getElementsByTagName('head')[0];

headTag.appendChild(tag);

var arrVideoStack = new Array();

arrVideoStack[0] = new Array(); // 0 = player reference, 1 = Display Elm ID, 2 = Video ID, 3 = IsLoaded

arrVideoStack[1] = new Array();

arrVideoStack[2] = new Array();

arrVideoStack[3] = new Array();

var iVideoCount = 0;

var bolYtReady = false;// Replace the 'ytplayer' element with an <iframe> and

// YouTube player after the API code downloads.

function onYouTubePlayerAPIReady() {

bolYtReady = true;

loadVideos();

}function registerNewVideo(strTargetElmId, strVideoId) {

strVideoId = strVideoId.replace('https://www.youtube.com/watch?v=', '');

strVideoId = strVideoId.replace('https://www.youtube.com/v/', '');

strVideoId = strVideoId.split('&')[0]; // In case there are any more parameters

arrVideoStack[0][iVideoCount] = null;

arrVideoStack[1][iVideoCount] = strTargetElmId;

arrVideoStack[2][iVideoCount] = strVideoId;

arrVideoStack[3][iVideoCount] = false; iVideoCount++;

if (bolYtReady) {

loadVideos();

}

}

function loadVideos() {
if (bolYtReady) {
if (iVideoCount > 0) {
for (i = 0; i < iVideoCount; i++) {
// If it hasn't already loaded, load it
if (!arrVideoStack[3][i]) {
arrVideoStack[0][i] = new YT.Player(arrVideoStack[1][i], {
height: '640',
width: '390',
videoId: arrVideoStack[2][i]
});
arrVideoStack[3][i] = true;
}
}
}
}
}
}

registerNewVideo('videoPlayer_Test1', 'dQw4w9WgXcQ');
registerNewVideo('videoPlayer_Test2', 'm2ATf01v4hw');
registerNewVideo('videoPlayer_Test3', 'YVhxcpItk_M');
</script>