Demo: $.jsonp JSONP error handling

Offers textStatus but no deferred capabilities.

by Adam Patridge

HTML

<ul class="debugOutput"></ul>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.6.2.js"></script>
<script type="text/javascript" src="http://jquery-jsonp.googlecode.com/files/jquery.jsonp-2.1.4.min.js"></script>

CSS

.hidden { display: none; }
.success { color: green; }
.error { color: red; }
.loading { position: fixed; bottom: 0; right: 0; }

JavaScript

$(function() {
    var padTwo = function(num) {
        return (num < 10) ? "0" + num : "" + num;
    },
        toSmallDateString = function(value) {
            return padTwo(value.getFullYear()) + "-" + padTwo(1 + value.getMonth()) + "-" + padTwo(value.getDate()) + "," + padTwo(value.getHours()) + ":" + padTwo(value.getMinutes()) + ":" + padTwo(value.getSeconds());
        },
        appendDebugOutput = function(message, cssClass) {
            var timestamp = new Date(),
                timestampStr = toSmallDateString(timestamp);
            $("<li>").addClass(cssClass).text(timestampStr + ": " + message).appendTo($(".debugOutput"));
            $("html, body").animate({
                scrollTop: $(document).height()
            }, 0);
            delete timestamp;
            delete timestampStr;
        },
        pollUrl = function(url, timeout) {
            appendDebugOutput("call started (timeout: " + timeout + ")");
            $.jsonp({
                url: url,
                callbackParameter: "callback",
                timeout: timeout || 3000,
                complete: function(xOptions, textStatus) {
                    appendDebugOutput("complete (" + textStatus + ")");
                },
                error: function(xOptions, textStatus) {
                    appendDebugOutput("error (" + textStatus + ")");
                }
            });
        };

    pollUrl("http://www.sierratradingpost.com/");
    setTimeout(pollUrl, 5000, "http://www.sierratradingpost.com/", 5);
    setTimeout(pollUrl, 6000, "http://www.sierratradingpost.com/", 3001);
});