SharePoint - disguise your long running AJAX calls

I have to confess I haven't had so much laugh in SharePoint for a long time.

OK, here's the problem:

  1. I'm calling a custom REST service that I've developed - the REST service checks a bunch of database records, as well as creating a new site and activate a number of features on that site. 
  2. Basically, it takes a while to run.  May be around 15 seconds.


Figure: Once you click this link it gets busy on the server.

Figure: Once it's clicked, I disable the link

Put up a dialog to tell the user to wait

The first thing we should do is put up a dialog to tell the user hey something's happening.

Waldek Mastykarz has an awesome article on how to do most of this, so I won't type out his code.

Figure: Here's my blocking dialog.  No close box.  It spins for about 15 seconds and then disappears when the AJAX call receives a success response.


But waiting for 15 seconds really gets boring.

You realize that you must use better messages, and update it as you wait. 





Here's the javascript code.


    var msgs = [
        "Calculating web paths",
        "Negotiating with site collection",
        "Creating empty site template",
        "Activating Features",
        "Synchronizing template",
        "Setting up form libraries",
        "Copying pages",
        "Configuring webparts",
        "Chasing chickens"];   
    var p = function(){
        if (waitDialog) {
            var msg = msgs[Math.floor(Math.random()*msgs.length)];
            waitDialog.get_html().getElementsByTagName('TD')[1].innerHTML = msg;
            setTimeout(p, 1000);

Create an array of status messages - these (aside from the chicken) are really what the REST service is doing.  I also create a function p, which choses a random message and updates the waitDialog.  Repeat every second.  When the AJAX call completes, it destroys the waitDialog, and set it to null.  This stops the setTimeout loop.


Some sort of magic happened

Suddenly, because things are updating on screen, the process doesn't seem long at all.  You click it, a few messages flash past, before you know it the site's created and ready to go.

So there you have it, the trick really is just a clever disguise. 

You show users random messages and distract them from the fact that they have to wait for 15 seconds.