GithubHelp home page GithubHelp logo

jquery-periodicalupdater's People

Contributors

bearded avatar cdesaintleger avatar colinharrington avatar duskhacker avatar fwhite avatar jondruse avatar mikesmullin avatar robertfischer avatar wattengard avatar wynst avatar xkickflip avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

jquery-periodicalupdater's Issues

Uncaught Illegal access reported by google chrome

First, I apologize if you are not using issue tracking via github. I am not all entirely sure if this is an issue with periodicalupdater.js but more an issue with the browser. But thought I would submit this at least for tracking purposes.

Anyhow, I am using the updater script to update a variable on the page if it changes. I tested in Safari 4, IE 7, Opera 10, and Firefox 3.6. Worked great in all of them. But when I popped open the page in Google Chrome (mac developer version 5.0.356.2) it is reporting an error. Here is what the console is showing.

XHR finished loading: "myurl-omitted".
Successful run! (In 'success') periodicalupdater.js.23
Status of call: success (In 'complete') periodicalupdater.js.23
Uncaught illegal acces periodicalupdater.js.122

It seems that this is the first run through of the script, not a subsequent run as the initial value is never inserted into the page. If you need any additional information to look into this I can see what I can dig up.

JSON encoded response throws SyntaxError: Unable to parse JSON string error

When attempting to poll an action that returns a JSON encoded string the plugin is throwing a SyntaxError (FF 3.6.3, Safari 4.0.5) when attempting to parse the response. On line 122 you're manually attempting to parse the response into a JSON object. I believe jQuery.ajax does the parsing for you automatically so this step should be unnecessary (at least with jQuery 1.4).

Good plugin though, thanks for sharing it with the world.

Feature Req: Add 'timeInterval' to .restart() in the handle

As it is right now calling the .restart() method restarts to the last known timeInterval.

It'd be great if restart could take an optional time and restart using that interval.

This is useful for other actions to trigger a proper reset/restart on the periodicalUpdater handle that is available in the return callback.

Never goes into the callback

Hello Robert,

Since yesterday, it seems that the callback is never called.
I've added a console.log() into it, and I never see it in the log history.
It happened since you commented the 'notmodified' condition on line 129.
I'm using jQuery 1.2.6 and the latest version of your library.

New feature: maxCallsCallback

I needed a way to be notified when PeriodicalUpdater stopped checking a remote URL due to the maxCalls being reached. I added the following line, which goes at the end of the getdata function.

function getdata(force) {
  // ...
  if (force || maxCalls === 0) {
    // ...
  } else {
    pu_log("NOT sending...");
    // added the following line (like autoStopCallback)
    if (settings.maxCallsCallback) { settings.maxCallsCallback(); }
  }
}

This works for my needs, but I didn't want to do a pull request since you may want to further refine it and/or call it something different.

if(console) doesn't work in IE 7

I know its not the 'best' solution but doing this makes the code work in IE 7.

try {
console.log("Resetting due to error: " + textStatus);
} catch(err) {}

Cancel PeriodicalUpdate

Hi,

Is it possible to cancel a specific PeriodicalUpdate cycle? And what about all the active cycles?

Thanks!

Periodical updater only retries one time no matter how I set it up

Here is my client code for the PeriodicalUpdater:

var checker = $.PeriodicalUpdater('/admin/koached_messaging_accounts/' + messaging_account_id + '/check',
{method: 'get',
data: '',
minTimeout: 2000,
maxTimeout: 2000,
multiplier: 1,
type: 'text',
maxCalls: 0,
autoStop: 20
}, function(data) {
if (data == 'Verified') {
checker.stop()
$('#' + network + '_status').text('Verified')
$('#' + network + '_status').attr('class', 'verified')
$('#' + network + '_button').attr('url', url.replace('verify', 'remove'))
$('#' + network + '_button').attr('value', 'Disconnect')
}
})

I can only get it to do the call twice. The callback is not being called (correctly, since the response data is not different on the 2nd call).

The first call prints out:

Successful run! (In 'success')
resetting timer to 2000.

The second call prints out:

Successful run! (In 'success')

and then no more runs. Seems pretty obvious that the reset call needs to be made. After reading the code, I can't see what's wrong, so I'll start doing some harder debugging.

Cannot handle multiple PeriodicalUpdaters

I encountered a problem, where I wanted to use multiple PeriodicalUpdaters to update multiple divs. Unfortunately, all of the divs were receiving the same data, which the last PeriodicalUpdater was receiving.

Updating data / settings between calls

I can't seem to update the data passed into the ajax call between calls. I wanted to pass in an ID/date of the last result to help limit the results in the calls. It looks like the extend() method copies the variables rather than preserve their reference. Is there a way to update any of the setting / parameters after the init?

Formatting issue

In jquery.periodicalupdater.js: line 75: looks like this closing brace should be moved to just after the return handle call.

In the current version, without this mod, I get a brace matching error and settings cannot be found below boostPeriod.

Well. here's my mod (untested):

/**
* PeriodicalUpdater - jQuery plugin for timed, decaying ajax calls
*
* http://www.360innovate.co.uk/blog/2009/03/periodicalupdater-for-jquery/
* http://enfranchisedmind.com/blog/posts/jquery-periodicalupdater-ajax-polling/
*
* Copyright (c) 2009-2012 by the following:
*  Frank White (http://customcode.info)
*  Robert Fischer (http://smokejumperit.com)
*  360innovate (http://www.360innovate.co.uk)
*
* Dual licensed under the MIT and GPL licenses:
* http://www.opensource.org/licenses/mit-license.php
* http://www.gnu.org/licenses/gpl.html
*
*/

(function ($) {
    var pu_log = function (msg) {
        try {
            console.log(msg);
        } catch (err) { }
    };

    // Now back to our regularly scheduled work
    $.PeriodicalUpdater = function(url, options, callback, autoStopCallback){
        var settings = jQuery.extend(true, {
                url: url,         // URL of ajax request
                cache: false,     // By default, don't allow caching
                method: 'GET',    // method; get or post
                data: '',         // array of values to be passed to the page - e.g. {name: "John", greeting: "hello"}
                minTimeout: 1000, // starting value for the timeout in milliseconds
                maxTimeout: 8000, // maximum length of time between requests
                multiplier: 2,    // if set to 2, timerInterval will double each time the response hasn't changed (up to maxTimeout)
                maxCalls: 0,      // maximum number of calls. 0 = no limit.
                autoStop: 0,       // automatically stop requests after this many returns of the same data. 0 = disabled
                verbose: 0
            }, options);

        // set some initial values, then begin
        var timer = null;
        var timerInterval = settings.minTimeout;
        var maxCalls = settings.maxCalls;
        var autoStop = settings.autoStop;
        var calls = 0;
        var noChange = 0;
        var originalMaxCalls = maxCalls;

        var reset_timer = function (interval) {
            if (timer !== null) {
                clearTimeout(timer);
            }
            timerInterval = interval;
            // pu_log('resetting timer to ' + timerInterval + '.');
            timer = setTimeout(getdata, timerInterval);
        };

        // Function to boost the timer
        var boostPeriod = function () {
            if (settings.multiplier >= 1) {
                before = timerInterval;
                timerInterval = timerInterval * settings.multiplier;

                if (timerInterval > settings.maxTimeout) {
                    timerInterval = settings.maxTimeout;
                }
                after = timerInterval;
                // pu_log('adjusting timer from ' + before + ' to ' + after + '.');
                reset_timer(timerInterval);
            }
            after = timerInterval;
            pu_log('adjusting timer from '+ before +' to '+ after +'.',1);
            reset_timer(timerInterval);
        };


        // Construct the settings for $.ajax based on settings
        var ajaxSettings = jQuery.extend(true, {}, settings);
        if (settings.type && !ajaxSettings.dataType) { ajaxSettings.dataType = settings.type; }
        if (settings.sendData) { ajaxSettings.data = settings.sendData; }
        ajaxSettings.type = settings.method; // 'type' is used internally for jQuery.  Who knew?
        ajaxSettings.ifModified = true;

        var handle = {
            restart: function () {
                maxCalls = originalMaxCalls;
                calls = 0;
                reset_timer(timerInterval);
                return;
            },
            stop: function () {
                maxCalls = -1;
                return;
            }
        };      

        // Create the function to get data
        // TODO It'd be nice to do the options.data check once (a la boostPeriod)
        function getdata() 
        {
            var toSend = jQuery.extend(true, {}, ajaxSettings); // jQuery screws with what you pass in
            if (typeof (options.data) == 'function') {
                toSend.data = options.data();
                if (toSend.data) {
                    // Handle transformations (only strings and objects are understood)
                    if (typeof (toSend.data) == "number") {
                        toSend.data = toSend.data.toString();
                    }
                }
            }

            if (maxCalls === 0) {
                $.ajax(toSend);
            } else if (maxCalls > 0 && calls < maxCalls) {
                $.ajax(toSend);
                calls++;
            }
        };

        // Implement the tricky behind logic
        var remoteData = null;
        var prevData = null;

        ajaxSettings.success = function (data) {
            // pu_log("Successful run! (In 'success')");
            remoteData = data;
            // timerInterval   = settings.minTimeout;
        };


        ajaxSettings.complete = function (xhr, success) 
        {
            // pu_log("Status of call: " + success + " (In 'complete')");
            if (maxCalls === -1) { return; }
            if (success == "success" || success == "notmodified") {
                var rawData = $.trim(xhr.responseText);
                if (rawData == 'STOP_AJAX_CALLS') {
                    handle.stop();
                    return;
                }
                if (prevData == rawData) {
                    if (autoStop > 0) {
                        noChange++;
                        if (noChange == autoStop) {
                            handle.stop();
                            if (autoStopCallback) { autoStopCallback(noChange); }
                            return;
                        }
                    }
                    boostPeriod();
                } else {
                    noChange = 0;
                    reset_timer(settings.minTimeout);
                    prevData = rawData;
                    if (remoteData === null) { remoteData = rawData; }
                    // jQuery 1.4+ $.ajax() automatically converts "data" into a JS Object for "type:json" requests now
                    // For compatibility with 1.4+ and pre1.4 jQuery only try to parse actual strings, skip when remoteData is already an Object
                    if ((ajaxSettings.dataType === 'json') && (typeof (remoteData) === 'string') && (success == "success")) {
                        remoteData = JSON.parse(remoteData);
                    }
                    if (settings.success) { settings.success(remoteData, success, xhr, handle); }
                    if (callback) { callback(remoteData, success, xhr, handle); }
                }
            }
            if (settings.complete) { settings.complete(xhr, success); }
            remoteData = null;
        };      
        ajaxSettings.error = function (xhr, textStatus) 
        {
            pu_log("Error message: " + textStatus + " (In 'error')", 2);
            if(textStatus != "notmodified") {
                prevData = null;
                reset_timer(settings.minTimeout);
            }
            if(settings.error) { settings.error(xhr, textStatus); }
        };

        // Make the first call
        $(function () {
                if (settings.runatonce) {
                    getdata();
                } else {
                    reset_timer(timerInterval);
                }
        });

        return handle;
    };
})(jQuery);

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.