Demo: $.ajax JSONP error handling

by Adam Patridge

HTML

<ul class="debugOutput"></ul>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.6.2.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 + ")");
            $.ajax({
                url: url,
                dataType: "jsonp",
                timeout: timeout || 3000,
            }).complete(function(xhr, textStatus) {
                appendDebugOutput("complete (" + textStatus + ")");
            }).error(function(xhr, 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);
});