jQuery AJAX

I’m sure there’s a perfectly good explanation for why the “always” function has two different signatures – one for requests that were successful and a different one for unsuccessful ones. But whatever their reason, they’re wrong. This is just plain stupid that you don’t know what kind of object the first and third parameters are. But they never asked me before they implemented it, so there’s nothing I can do about it…

var jqXHR = jQuery.ajax(ajaxParams);
jqXHR.done(function(data, textStatus, jqXHR) {});
jqXHR.fail(function(jqXHR, textStatus, errorThrown) {});
jqXHR.always(function(data|jqXHR, textStatus, jqXHR|errorThrown ) { });
The ajaxParams object contains lots of different options - the ones I generally use are as follows:
    // absolute or relative
    url: "/path/to/some/url",
    // will you be receiving "json", "html", "text", or "xml" back
    // 99% of the time I use json or html. If json, then the result will already
    // be parsed into a javascript object.
    dataType: "json",
    // what kind of data you are posting
    // 'application/x-www-form-urlencoded; charset=UTF-8' is the default
    contentType: "application/json; charset=utf-8",
    // This one is fun. If you're posting form-urlencoded, then this can 
    // either be a string representing the form post, like name=John&age=34
    // or it can be a javascript object and jQuery will automatically build
    // the string: { name: "John", age: 34 }
    // However, if you are posting JSON, then it needs to be a JSON string (not
    // an object, but the JSON representation of that object):
    // JSON.stringify({ name: "John", age: 34 })
    data: myData

There's a lot more you can do with it – see the documentation.


Popular posts from this blog

DotNet CLI

Switch Expressions

Nullable reference types