Simple AJAX Polling Plugin for jQuery

Published on Author nickriggs24 Comments

I’m currently working on Html5 application that launches AJAX HTTP requests that can potentially be long running. Furthermore, the user can launch a bunch of them at a time. In a perfect world the application would wait for the server to respond, but that’s not possible since HTTP 1.1 dictates that a browser should have no more than two concurrent connections open to a server. This causes the browser to appear locked up when two long running requests are active.

I decided I would use a polling solution for these long running requests. Basically, when the client sent a request to the server for the data, the server would begin (or continue) it’s work and respond to the client request immediately. The response would contain a data element signalling the client that the server was still working on the request. The client would wait a certain interval and try again, and continue this process until the response contained expected data.

I looked around for a jQuery plugin to help me, but didn’t come up with anything that did exactly what I wanted – so I wrote one. My specific need was that I didn’t want a simple interval based timing, meaning for example: Try every 500 milliseconds. Instead I wanted to scale (over a duration) the amount of time that the client waited before sending subsequent requests. Starting out very low for the many requests that come back almost immediately, and progressing to a much longer wait for the requests that are taking a long time.

I extended the built in jQuery $.ajax(), $.post() and $.get() functions, here is an example of making a polling call with ajaxPolling.js:

$.ajaxPoll({
    url: "/Query/Run",
    type: "POST",
    data: { queryId: 1234 },
    dataType: "json",
    success: function(data) {
        alert(data.result);
    }
});

In this example, the polling code decides when a request represents a completed job by evaluating the default successCondition, which is defined globally as:

successCondition: function(result) {
    if (result != null) {
        try {
            return eval(result)["complete"];
        }
        catch (ex) {
            return false;
        }
    }

    return false;
}

The successCondition can be overridden globally or locally on an single call:

Globally:

$.ajaxPollSettings.successCondition = function(result) {
    return result != null; // custom condition goes here.
}

Locally:

$.ajaxPoll({
    url: "/Query/Run",
    type: "POST",
    data: { queryId: 1234 },
    dataType: "json",
    successCondition: function(result) {
        return result != null; // custom condition goes here.
    },
    success: function(data) {
        alert(data.result);
    }
});

By default, the polling type is “interval”. It’s doing a simple retry event X milliseconds. For my application, I’d like to have a more complicated “timed” set up that starts out retrying at 250 milliseconds and works its way up to retrying every 5,000 milliseconds over 60 seconds. To set this up globally for my application:

$.ajaxPollSettings.pollingType = "timed";
$.ajaxPollSettings.interval = 250;
$.ajaxPollSettings.maxInterval = 5000;
$.ajaxPollSettings.durationUntilMaxInterval = 6000;

Now any calls I make to $.ajaxPoll(), $.getPoll() or $.postPoll() will use my “timed” settings.

This plugin gives me a quick way to add a client side polling solution to my applications. Keep in mind that implemented correctly, the server is involved in this solution as well, meaning that in a best-case scenario: calls made to the server respond almost immediately with either a flag signaling that the server is still working or the actually result. In the future, I’ll post a sample implementation of an ASP.MVC application that works with the plugin.

First Draft Source Code: jQuery ajaxPoll Plugin

See Also:

24 Responses to Simple AJAX Polling Plugin for jQuery

  1. That’s an interesting plugin, seems quite useful.

    May I just make one suggestion? You could use the return value of the success function as the success condition itself.

    This is because there can probably much coupled logic going on in both success and successCondition functions; also, by using the return value of the success handling function, it can be easier for the developer to condition the continuation of the poll to something that may not be in the contents from the ajax call (such as if a list has been filled in the page of something like that).

    Great work nonetheless.

  2. This is as useful as a chocolate teapot. Although it will poll away (confirmed by Firebug) I could not get this plugin to actually do something useful. Without an example to show me how I can’t use this code!

  3. Nick-

    Thanks for this. Super useful.

    I noticed on tragic flaw in your code though, that is very easily fixed:

    line 73:
    jQuery.ajax(options);

    should be:
    return jQuery.ajax(options);

    without the return, there is no way to keep track of these , and you can’t abort / etc. you left out the jquery functionality that returns xhtml request objects.

    • Yeah, I guess the best thing to do would be to return an object that has an abort() method on it. It would handle aborting the current operation and suspending future attempts. I’ll take a look at doing that.

  4. Hey, great work! Although, I too, would like to have a demo. I’m trying to read your code on how to best implement, but my success callback is only being fired once. successCondition is fired repeatedly tho. Is this by design, what am I missing? A quick demo on how to implement would be great–thanks

    • @Jake, your successCondition will fire every time a polling request returns from the server. Once the successCondition is met, success is called once, and future polling operations are suspended. If you want to re-poll, you will need restart the entire process in your success handler.

  5. Hi,
    In the functtion where you are passing in the ‘queryId’ value, I want to pass an incrementing value in here, I’m guessing that you could increment that value in the ‘successCondition’ function?

    How would you go about that?

    Thanks
    Shaun

  6. 可能是我安装其它主题带来的恶意代码?或者是一些下载管理插件自动生成的文件?文件名为:template-down.php内容:麻烦分析一下,是不是恶意的代码. 如果是,有什么后果, 怎么修复下.安装过3个下载管理插件:WP Facebox downloaglightwindow-moHacklog-DownloadManager都是从官网下载,或后台直接搜索安装的. 2012 年 10 月 7 日 下午 10:43

  7. PippinThank for getting back to me.This first sotcien is the plugin file (excluding plugin headers)12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364//Load Ajax Scripts For Admin function TTET_Load_Ajax_Frontend_Scripts wp_enqueue_script ‘TTET-Ajax-Frontend’, plugin_dir_url __FILE__ . ‘js/TTET-Ajax-Front.js’, array ‘jquery’ ;wp_localize_script ‘TTET-Ajax-Admin’, ‘TTET_vars’, array ‘TTET_nonce’ = wp_create_nonce ‘TTET_nonce’ ;wp_localize_script ‘WP-Ajax’, ‘ttftajax’, array ‘ajaxurl’ = admin_url ‘admin-ajax.php’ ;wp_enqueue_script ‘json-form’ ; add_action ‘wp_enqueue_scripts’, ‘TTET_Load_Ajax_Frontend_Scripts’ ; //Populate Frontend Page Content Through Shortcode function TTET_Ajax_Frontend_Content global $TTET_Ajax_Settings;? 220810 Ajax Demo img id= TTET_Ajax_Loading src= ” class=”waiting” style=”display:none;” ?php} add_shortcode( TTET_Ajax_Front , TTET_Ajax_Frontend_Content ); // Process Ajax Request function TTET_Process_Frontend_Ajax(){ if( !isset( $_POST[ TTET_nonce ] ) || !wp_verify_nonce($_POST[ TTET_nonce ], TTET_nonce )){echo Permision Check Failure’; die();} $TTET_Results = get_posts(array(‘post_type’ = ‘page’, ‘posts_per_page’ = 10)); if ( $TTET_Results ) : echo ”; foreach($TTET_Results as $TTET_Result) { echo ” . get_the_title($TTET_Result- ID) . ”; } echo ”; else : echo ‘No Results Found’; endif; die(); } add_action (‘wp_ajax_nopriv_TTET_Get_Front_Results’, ‘TTET_Process_Frontend_Ajax’);and the following is the JS file1234567891011121314151617181920212223jQuery document .ready function $ $ ‘#TTET-Ajax-Form’ .submit function $ ‘#TTET_Ajax_Loading’ .show ; data = action: ‘TTET_Get_Front_Results’,TTET_nonce: TTET_vars.TTET_nonce ; $.post ttftajax.ajaxurl, data, function response $ ‘#TTET_Results’ .html response ;$ ‘#TTET_Ajax_Loading’ .hide ; ; return false; ; ;I hope you can help me find what is probably staring me in the face.ThanksColin

  8. The thingsome of these kinds of alarms installed by the learner who should be in different types of car you own a Japanese Coupe, we have been denied a claim you bedon’t know how you will have car insurance, you have if you are driving a vehicle in a teen to your insurer be made available to make a complete these thencould always opt to visit the government for the car costs, many people are aware of if you are acquiring protection with reliable customer service is an important subject. I Ian automatic payment deductions from the auto insurance market is very accessible. Legit car insurance agency from an insurance cover, a car on rent for the rainy day savings account depositoffering? Auto insurance is a statistically higher in flow of the car insurance can be different from each other. Each one displays a lot of money. One thing that most giveas you are currently using more than ten pounds and 14,999 pounds and comparing in order for the best. You should save lot of vehicles covered by this coverage. If usingauto insurance under 25? Everyone knows that if you were an insurance provider pays less than three years old and not too high, then the victim of the things that havethere are companies that provide services that you check out quotes without properly knowing either accepts or declines the car you drive a car does not impress any insurance policy lookstechnologically savvy. They have demonstrated a high risk because people who apply for claim. Coverage varies from every race and sex.

Leave a Reply

Your email address will not be published. Required fields are marked *