npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

jquery-ajax-chain

v1.0.8

Published

jQuery helper class meant to ease up the process of making multiple synchronously chained Ajax calls.

Downloads

104

Readme

jQuery Ajax Chain

The $.AjaxChain jQuery helper class allows to perform multiple synchronously chained Ajax calls; its optional settings make possible to filter data and pass it between succeeding calls, manage custom errors, create caching mechanisms and conditionally halt queue progression.

Documentation

Note: although being written in plain JavaScript, this library adopts the TypeScript interface definition standard to document its features.

Constructor

| name | description | | :-- | :-- | | $.AjaxChain():JQueryAjaxChain | The $.ajaxChain helper class extends the JQueryPromise<T> object (http://api.jquery.com/Types/#Promise) with custom methods. |

Public methods

| name | chainable | description | | :-- | :-- | :-- | | enqueue(confObj: AjaxChainConfiguration | AjaxChainConfiguration[]):JQueryAjaxChain | yes | Enqueues one or more configuration objects for later processing. | | dequeue():JQueryAjaxChain | yes | Sequentially and synchronously dequeues the configuration objects enqueued via enqueue() method in the order they were added, triggering the related Ajax calls. | | clearQueue():JQueryAjaxChain | yes | Clears the currently queued configuration objects. | | state():string | no | jQuery API Reference. | | then<U>(doneFilter: (value?: T, ...values: any[]) => U | JQueryPromise<U>, failFilter?: (...reasons: any[]) => any, progressFilter?: (...progression: any[]) => any):JQueryPromise<U> | yes | jQuery API Reference. | | done(doneCallback1?: JQueryPromiseCallback<T> | JQueryPromiseCallback<T>[], ...doneCallbackN: Array<JQueryPromiseCallback<T> | JQueryPromiseCallback<T>[]>):JQueryPromise<T> | yes | jQuery API Reference. | | fail(failCallback1?: JQueryPromiseCallback<any>|JQueryPromiseCallback<any>[], ...failCallbacksN: Array<JQueryPromiseCallback<any> | JQueryPromiseCallback<any>[]>):JQueryPromise<T> | yes | jQuery API Reference. | | always(alwaysCallback1?: JQueryPromiseCallback<any> | JQueryPromiseCallback<any>[], ...alwaysCallbacksN: Array<JQueryPromiseCallback<any> | JQueryPromiseCallback<any>[]>):JQueryPromise<T> | yes | jQuery API Reference. | | progress(progressCallback1?: JQueryPromiseCallback<any> | JQueryPromiseCallback<any>[], ...progressCallbackN: Array<JQueryPromiseCallback<any> | JQueryPromiseCallback<any>[]>):JQueryPromise<T> | yes | jQuery API Reference. |

Callback functions arguments

Note: differently from the original jQuery implementation, callbacks specified as arguments of then(), done(), fail(), always() methods get passed an array of responses: [response[,responseN, ...]]. Furthermore, callbacks specified as arguments of progress() method get passed an object structured as follows:

| key | value | | :-- | :-- | | index:number | Dequeued Ajax call zero-based index | | label:string | Dequeued Ajax call label, either user-defined or randomly generated | | data:any | Dequeued Ajax call response |

Configuration object

| key | description | | :-- | :-- | | ajaxSettings:JQueryAjaxSettings | jQuery $.ajax method settings. | | label?:string | Configuration object label (see progress() callback functions argument). | | transform?:Function | Returning a truthy value allows to arbitrarily overwrite the next queued Ajax call 'data' property value specified in the original jQuery $.ajax method configuration object ('ajaxSettings'). See example #1. | | appendToUrl?:Function | Returning a truthy value (String) allows to append string fragments to the next queued Ajax call 'url' property value specified in original jQuery $.ajax method configuration object ('ajaxSettings'); handy when dealing with semantic urls. See example #2. | | hasErrors?:Function | Returning a truthy value determines any registered fail callback(s) to be called immediately, passing the former as an argument; the queue is then rejected. See example #3. | | hasCache?:Function | Returning a truthy value allows to prevent the related Ajax call from being executed, passing the former as a parameter to any registered handler(s); useful to create caching mechanisms. See example #4. | | hasHaltingCapabilities?:Function | Returning a truthy value prevents the queue from further progressing to the succeeding Ajax calls; the queue is then resolved. See example #5. | | isSkippable?:Function | Returning a truthy value prevents the queue from being halted in case of $.Ajax error. See example #6. |

Note: All functions specified as values of optional configuration object properties (marked with a question mark) are passed the dequeued Ajax call response as argument.

Examples

Typical setup

var ajaxChain = new $.AjaxChain();
ajaxChain.enqueue([configurationObject[,configurationObjectN, ... ]])
         .dequeue()
         .then(doneCallback, failCallback, progressCallback);

Common configuration patterns

<!-- The succeeding examples assume the following xml response: -->

<?xml version = "1.0"?>
<items>
    <item id="000001">
        <name>Item #1</name>
        <categoryId>1</categoryId>
    </item>
    <item id="000002">
        <name>Item #2</name>
        <categoryId>2</categoryId>
    </item>
    <item id="000003">
        <name>Item #3</name>
        <categoryId>3</categoryId>
    </item>
</items>
1. Dynamically passing data between succeeding Ajax calls:
var ajaxChain,
    configurationObj1,
    configurationObj2;
ajaxChain = new $.AjaxChain();
configurationObj1 = {
    ajaxSettings: {
        type: "GET",
        dataType: "xml",
        url: "/items"
   },
   transform: function(xmlResponse){
        var nextCallDataObj;
        if (xmlResponse) {
            nextCallDataObj = {
                id: $(xmlResponse).find('item')
                                  .first().attr('id')
            };                   
            return nextCallDataObj;               
        }                  
        return false;              
   }
};
// configuration object omitted for brevity
configurationObj2 = { . . . };
ajaxChain.enqueue([configurationObj1, configurationObj2])
         .dequeue()
         .then(doneCallback, failCallback, progressCallback);
2. Dynamically appending url fragments between succeeding Ajax calls:
var ajaxChain,
    configurationObj1,
    configurationObj2;
ajaxChain = new $.AjaxChain();
configurationObj1 = {
    ajaxSettings: {
        type: "GET",
        dataType: "xml",
        url: "/items"
    },
    appendToUrl: function(xmlResponse){
        var nextCallUrlFragment = "";
        if (xmlResponse) {
            nextCallUrlFragment = "/" + $(xmlResponse).find('item')
                                                      .first()
                                                      .attr('id');
        };                 
        return nextCallUrlFragment;               
    }               
};
// configuration object omitted for brevity
configurationObj2 = { . . . };
ajaxChain.enqueue([configurationObj1, configurationObj2])
         .dequeue()
         .then(doneCallback, failCallback, progressCallback);
3. Dynamically resolving queue upon custom errors:
var ajaxChain,
    configurationObj1,
    configurationObj2;
ajaxChain = new $.AjaxChain();
configurationObj1 = {
    ajaxSettings: {
        type: "GET",
        dataType: "xml",
        url: "/items"
    },
    hasErrors: function(xmlResponse){
        var $tempXmlResponse,
            categoryFilter = "1";
        $tempXmlResponse = $(xmlResponse);
        // check current Ajax call response for errors
        if ($tempXmlResponse.find("item").eq(0)
                            .find("categoryId")
                            .text()
                            .indexOf(categoryFilter) !== -1) {
            return "[Exception] forbidden category id: " + categoryFilter;
        }
        return false;         
   }
};
// configuration object omitted for brevity
configurationObj2 = { . . . };
ajaxChain.enqueue([configurationObj1, configurationObj2])
         .dequeue()
         .then(doneCallback, failCallback, progressCallback);
4. Creating caching mechanisms:
var ajaxChain,
    configurationObj1,
    configurationObj2;
ajaxChain = new $.AjaxChain();
configurationObj1 = {
    ajaxSettings: {
        type: "GET",
        dataType: "xml",
        url: "/items"
    },
    hasCache: function(xmlResponse){  
        // retrieve possible cached results
        if (itemsCollection.length) {
            return itemsCollection.toJSON();
        }
        return false;     
    }
};
// configuration object omitted for brevity
configurationObj2 = { . . . };
ajaxChain.enqueue([configurationObj1, configurationObj2])
         .dequeue()
         .then(doneCallback, failCallback, progressCallback);
5. Halting queue upon conditional logic:
var ajaxChain,
    configurationObj1,
    configurationObj2;
ajaxChain = new $.AjaxChain();
configurationObj1 = {
    ajaxSettings: {
        type: "GET",
        dataType: "xml",
        url: "/items"
    },
    hasHaltingCapabilities: function(xmlResponse){
        var $tempXmlResponse;
        $tempXmlResponse = $(xmlResponse);
        if ($tempXmlResponse.find("item").eq(0)
                            .find("categoryId")
                            .text().indexOf("1") !== -1) {
            return true;
        }
        return false;        
    }
};
// configuration object omitted for brevity
configurationObj2 = { . . . };
ajaxChain.enqueue([configurationObj1, configurationObj2])
         .dequeue()
         .then(doneCallback, failCallback, progressCallback);
6. Preventing a queue from being halted in case of $.Ajax error:
var ajaxChain,
    configurationObj1,
    configurationObj2;
ajaxChain = new $.AjaxChain();
configurationObj1 = {
    ajaxSettings: {
        type: "GET",
        dataType: "xml",
        url: "/items"
    },
    isSkippable: function(xmlResponse){
        return true;
    }
};
// configuration object omitted for brevity
configurationObj2 = { . . . };
ajaxChain.enqueue([configurationObj1, configurationObj2])
         .dequeue()
         .then(doneCallback, failCallback, progressCallback);

TypeScript

Visual Studio (NuGet)
  1. Open the Package Manager Console
  2. Install-Package jquery-ajax-chain.TypeScript.DefinitelyTyped
Node.js (TSD)
  1. Open a shell in your project's scripts folder
  2. npm install tsd -g
  3. tsd install jquery-ajax-chain --save

Testing

Headless
  1. Open a shell in the package root folder
  2. npm install
  3. bower install
  4. grunt test:headless
Browser
  1. Open a shell in the package root folder
  2. npm install
  3. bower install
  4. grunt test:browser (--port option available, e.g.: grunt test:browser --port=8083)

Note: this project was packaged with grunt-init-jquery.