jQuery Ajax Setup Methods Uses

If you are a web developer you must have used jquery. You may be familiar with ajax setup methods. https://api.jquery.com/jQuery.ajaxSetup/

Here I am going to explain some tips and tricks using these methods that can be really helpful in some scenarios.

If you have integrated some third party websites inside an iframe or in a div, definitely you may have limited access to ajax requests. In this scenario, ajax setup methods are can be really handy.

If you want to append some query parameter in a URL or for every request. You can use “beforeSend” method. You can add a new http header or can change an existing one.

If you want to change the ajax response (filter data) you may use “dataFilter” method.

If you want to do some post ajax function especially if you don’t have control of request flow you may use “ajaxComplete”.

Below is the code example of these methods.

$.ajaxSetup({

beforeSend: function( xhr,settings ) {
    console.log(this.url);
    //You may set http headers as well
    xhr.setRequestHeader('content', 'application/json');
    //this.url provides the current ajax request URI
    if(this.url == "Here the url where you want to add some parameter before send" ) 
    {
        var paramObj = parseParams(settings.data);
        //You may add as many parameters as you want
        paramObj.newParam = "It will be added as parameter with current ajax url";
        settings.data = $.param( paramObj );
    }

},
dataFilter: function(data, type) {
if(this.url.indexOf("search some part of a url") >=0 ){

    if(type == 'json' ) {
                //convert json to object
              var parsed_data = JSON.parse(data);
              $.each(parsed_data, function(i, item)
              {
                  //Change the value that we received from server
                item.name = "some magic name";
              });
              return JSON.stringify(parsed_data);
        }
    }
    return data;
},
ajaxComplete: function() {
    //Here the ajax request is completed you may done some post ajax action here.
}
});

Please share this post:
Distinguished Engineer Java, PHP, Spring, Mysql
Posts created 11

One thought on “jQuery Ajax Setup Methods Uses

Ask a Question

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Related Posts

Begin typing your search term above and press enter to search. Press ESC to cancel.

%d bloggers like this: