Showing posts with label JQuery. Show all posts
Showing posts with label JQuery. Show all posts

Saturday, September 27, 2014

Understanding Deferred in JQuery

Simplest example of ajax request in JQuery.

        $.ajax('http://ip.jsontest.com/', {
            success: function (result) {
                console.log('success');
            },
            error: function (err) {
                console.log('error');
            }
        });

Result of success callback function will have 3 parameters, which are "Anything (any type of) data, String textStatus, jqXHR jqXHR".


You can check the state of jqXHR object using jqXHR().state(), If you check with beforeSend event, you can see the state is pending before request is sent. Sometimes you'll get “No 'Access-Control-Allow-Origin' header is present on the requested resource” error.

$.ajax also returns jqXHR object. You can assign multiple callbacks to this.

        var a = $.ajax({
            url: 'http://jsonplaceholder.typicode.com/posts/1',
            success: function (data) {
                console.log(data);
            },
            error: function (data) {
                console.log(data);
            }
        });

        a.done(function (result) {
            console.log('done : ' + result);
        });

        a.then(function (result) {
            console.log('then : ' + result);
        });

        a.error(function (result) {
            console.log('error : ' + result);
        });

here after sending the ajax request, the object immediately returns and other callbacks are attached. Still the ajax state is pending, If success callback get hits, state becomes resolved and then callbacks are called.

If it hits error state is rejected. done or then callbacks won'get called but error callback will get called. then() can also have failCallback attached like below,

        a.then(function (result) {
            console.log('then : ' + result);
        }, errorCallback);

        function errorCallback(err) {
            console.log(err);
        }

If you specify this, errorCallback will get called if an error occurs.

jQuery.when()
accepts one or more objects and provide a way to execute callback functions. Usually deferred. If single Deferred is passed, its Promise is returned.

            function ajaxCall() {
                return $.ajax({
                    url: 'http://jsonplaceholder.typicode.com/posts/1',
                })
                .done(function (data) {
                    console.log(data);
                })
                .fail(function (data) {
                    console.log(data);
                })
            }

            function function2() {
                debugger;
            }

            var a = $.when(ajaxCall());
            a.then(function2);

If a single argument is passed to $.when which is not a Deferred or a promise, It'll be treated as resolved and attached callbacks will be called. Above if you don't return anything from ajaxCall(), a will be resolved and function2 will be executed without waiting for ajaxCall to be finished. Since your Deferred never gets rejected, fail callbacks are never get called. If Deferred resolved with no value, callbacks will get undefined value.

If you return ajax, a will be at pending state until ajaxCall() is finished and then only function2 gets executed.

deferred.then()
Add handlers to be called when deferred object is resolved, rejected or pending.

If we expand on the example above, here you can attach fallCallbacks as well.

            function failPath() {
                debugger;
            }

            var a = $.when(ajaxCall());
            a.then(happyPath, failPath);

deferred.done()
Handlers to be called when deferred object is resolved

        var defer = $.Deferred();
        defer.done(function (val) {
            console.log(val);
        });

        defer.then(function (val) {
            console.log(val);
        }, function (val) {
            console.log(val);
        });

if defer.resolve()
done callback and then's done callback will be called

if defer.reject()
done callback won't get called. then's fail callback will get called.

You can check active Ajax requests using $.active function. See this


Monday, March 10, 2014

Deferred in JQuery

Web applications are kept alive by data. These data usually retrieved from data sources. AJAX (Asynchronous JavaScript and XML) is a technique used to communicate with web servers to send and receive data asynchronously. Often you'll send a ajax request, wait for data to come inside callbacks and execute rest of the flow. Ajax uses XMLHttpRequest object to communicate with server side.


XMLHttpRequest object
Is used to exchange data between client and server. Using this you can update web pages without reloading or send data to server in background.

Below is how you can create a simple ajax request using jQuery. You can pass object to as a parameter which contains settings for the ajax request. jQuery.ajax() will return a jqXHR object. jqXHR is a superset of native XMLHttpRequest. As of jQuery 1.5, jqXHR object implements the Promise interface.

There are variety of options you can use to customize the ajax requests.



Also you can use jQuery.ajaxSetup() to set defaults for future Ajax requests but using this not recommended.

When you have multiple ajax requests to send you'll need some mechanism to chain them to have correct sequencing you desire. Also you'll need to make the requests asynchronously to make browser not getting freezed (you can make Ajax requests synchronous but it is not advisable). in jQuery you can use Deferred for this.

Wednesday, January 1, 2014

jQuery Useful Functions

each()
Is a generic iterator function, which can be used with objects and arrays.
each vs for loop$.each vs $().each vs for

map()
Returns a new array with changes applied
Difference between map and each

extend()
Merges two or more objects into to the first object and returns it.

data()
data

inArray()
Checks if an item is in array

noop()
declares an empty function. Rather than passing an anonymous functions you can use this.

proxy()
Takes a function and returns a function which will always have a particular context. 

JQuery Tips and Tricks



Parsing in JQuery

Use JQuery.parseJSON() to convert a JSON string to a JavaScript object. Also there are other parsing options available in JQuery to parse string to XML (jQuery.parseXML()) and to parse a string into array of DOM elements (jQuery.parseHTML()).


Use Papa Parse to convert CSVs. 



AJAX Requests

When sending AJAX Get requests to the server, jQuery adds _ Query Parameter to the request URL. This is appended to get rid of caching in IE. This will be added only if cache option is set to false. The parameter is a timestamp. Also see this article


Powered by Blogger.


Software Architect at Surge Global/ Certified Scrum Master

Experienced in Product Design, Software Engineering, Team management and Practicing Agile methodologies.

Search This Blog

Facebook