Using jQuery.ajaxSetup() To Accumulate Global Data Parameters For AJAX Requests

Posted February 17, 2011 at 10:20 AM by Ben Nadel

Tags: Javascript / DHTML

In jQuery, we have the ability to make one-off AJAX requests with the $.ajax() method, or any one of its short-hand versions (ie. get(), post(), etc.). We also have the $.ajaxSetup() function which allows us to define globally-shared properties for all the AJAX requests made within a single page. Up until yesterday, I had thought that $.ajaxSetup() worked in a substitution-only manner; but, according to Cody Lindley it appears that the "data" value is actually accumulative.

 
 
 
 
 
 
Cody Lindley On $.ajaxSetup(). 
 
 
 

Once I saw his tweet, I needed to see the accumulation for myself; so, I set up this quick little demo. In the following code, you'll see that I am using two $.ajaxSetup() calls followed by an $.ajax() request.

  • <!DOCTYPE html>
  • <html>
  • <head>
  • <title>Using $.ajaxSetup() To Accumulate Data</title>
  • <script type="text/javascript" src="./jquery-1.5.js"></script>
  • <script type="text/javascript">
  •  
  •  
  • // Set up some default data for jQuery-driven AJAX requests.
  • // In general, ajaxSetup() builds the options hash; but when
  • // it comes to data, the effect is accumulative.
  • $.ajaxSetup({
  • data: {
  • username: "sakura",
  • password: "Hadoken!!!"
  • },
  • dataType: "jsonp"
  • });
  •  
  • // Add another data item to the global confiruguration.
  • $.ajaxSetup({
  • data: {
  • gameID: "SF"
  • }
  • });
  •  
  •  
  • // -------------------------------------------------- //
  • // -------------------------------------------------- //
  •  
  •  
  • // Now make an AJAX request in which we add additional
  • // data points to teh outgoing request.
  • $.ajax({
  • type: "get",
  • url: "./ajax_setup_data.htm",
  • data: {
  • id: 4,
  • name: "Jill",
  • gameID: undefined
  • },
  • complete: function(){
  • console.log( "Request complete." );
  • }
  • });
  •  
  •  
  • </script>
  • </head>
  • <body>
  • <!-- Intentionally left blank. -->
  • </body>
  • </html>

Here, we are building up the data key for our AJAX requests using two different $.ajaxSetup() requests; then, we build up the data key even further at the point of request. When we run this code and examine the requests parameters, we can clearly see that data key is accumulative:

 
 
 
 
 
 
jQuery $.ajaxSetup() Method Will Accumulate Data Values. 
 
 
 

As you can see, this outgoing request includes the data points provided by both $.ajaxSetup() calls and the final $.ajax() request. The one caveat to be aware of, however, is that "undefined" values won't subtract data points. If you look at my $.ajax() request, you'll notice that I am passing in the "gameID" value as an undefined value; however, if you look at the outgoing parameters, you'll see that the gameID is being sent as "SF" - the value provided by $.ajaxSetup(). While undefined values don't get sent in an AJAX request, we can also see that in the case of $.ajaxSetup(), undefined values don't remove an existing data point.

Pretty cool stuff. I've not made too much use of the $.ajaxSetup() method to date; but, knowing how it works can only help me better decide when using it would be appropriate. It's probably time that I start diving back into client-side application architecture.




Reader Comments

Feb 17, 2011 at 10:37 AM // reply »
1 Comments

This is a very useful feature. I use it all the time with CSRF tokens. You can just append the token to every ajax request, to simply add the feature. Google and all major frameworks recently discovered the even local ajax calls are vulnerable.

"Recently, engineers at Google made members of the Ruby on Rails development team aware of a combination of browser plugins and redirects which can allow an attacker to provide custom HTTP headers on a request to any website. This can allow a forged request to appear to be an AJAX request, thereby defeating CSRF protection which trusts the same-origin nature of AJAX requests."

All in all cool stuff


Feb 17, 2011 at 10:48 AM // reply »
10,743 Comments

@Michael,

Wouldn't it be nice if we lived in a world where security wasn't a constant issue :) It's good to know you're making use of this function, though. I need to practice my client-side programming a bit more - see where this kind of thing can really be put to use.


Jul 13, 2011 at 2:42 PM // reply »
2 Comments

Very usefull! Now it makes sense that ajax calls with jQuery are easier!


Jul 14, 2011 at 4:31 AM // reply »
2 Comments

It doesn't work if you put query string (like x=hello) in data param within $.ajax(). The 'global' data will get overwritten.


Jul 20, 2011 at 1:46 PM // reply »
10,743 Comments

@Florencia,

Glad that was useful :)

@Quincy,

I am not sure I understand what you mean?


Jul 25, 2011 at 3:46 AM // reply »
2 Comments

@Ben,

Data parameter can either be object or string(query string)
http://api.jquery.com/jQuery.ajax/

If you provide a query string as "data" in $.ajax(), the "data" specified using $.ajaxSetup would not be merged but got overwritten instead.

So if we want to use this "global data" feature, make sure no js libraries you are using will modify the "data" param using a query string. (e.g. jQuery Form Plugin)


Jan 14, 2012 at 11:42 AM // reply »
1 Comments

Also note that this only works with jQuery 1.5+.
If you are using jQuery 1.4 data in $.ajaxSetup is overwritten, not accumulated.


Mar 18, 2012 at 9:18 AM // reply »
1 Comments

@Quincy,

As an additional FYI I would like to add that

  • jQuery.serialize()

also produces a query string, something that I found out the hard way now when I tried this.

Should've read the comments here before trying to figure out what was wrong.. :-P


Post A Comment

Comment Etiquette: Please do not post spam. Please keep the comments on-topic. Please do not post unrelated questions or large chunks of code. And, above all, please be nice to each other - we're trying to have a good conversation here.

Please review the following issues:

Author Name:


Author Email:

Author Website:

Comment:

Supported HTML tags for formatting: <strong>bold</strong>   <em>italic</em>   <code>code</code>







  • Help Wanted - Find Your Next ColdFusion Job
InVision App - Prototyping Made Beautiful With Prototyping Tools Ben Nadel's Company - Epicenter Consulting Recent Blog Comments
May 16, 2012 at 8:18 PM
Best Of ColdFusion 10 Contest Entry - HTML Email Utility
Just found this, looks good! I'm trying to run it on local, it's the 64bit version and I'm experiencing horrible lag. On average the generate.cfm processes the content change in 60-90 seconds. I've ... read »
May 16, 2012 at 6:40 PM
Maintaining Sessions Across Multiple ColdFusion CFHttp Requests
I am trying to integrate this CFHTTPsession into an application that will log into zeekrewards.com to post ads and I am not having any luck. The code works perfectly for logging into other websites, ... read »
May 16, 2012 at 2:44 PM
Creating A Sometimes-Fixed-Position Element With jQuery
Thank you, very useful technique! Worked like a charm. ... read »
May 16, 2012 at 1:58 PM
Movies As A Religious Experience
Acting can, in a way, ruin the movie-goer's experience. I used to be able to get so caught up in movies and their plots, and totally engaged. But lately, I haven't been able to as much with a lot o ... read »
May 16, 2012 at 1:52 PM
The Science Of Optimal Post-Exercise Nutrition
children of this age eat very less vegetables so u can opt for salads they will like it also carrot ,cucumber,onion and as far as pulses are concerned u can boil them ,give him along with mashed rice ... read »
May 16, 2012 at 1:34 PM
Strange ColdFusion JRUN Stack Overflow Error
Hey, Recently I updated my jrun4 using the latest updater 7 and now i am having memory issues :(:(:( any help is appreciated ... read »
May 16, 2012 at 9:56 AM
ColdFusion 10 Beta, Apache Tomcat, And Symbolic Links On Mac OSX
Hi, Now that ColdFusion 10 is out I have stumbled over this as well and I cannot figure out the proper solution. We're running virtual hosts via Apache2; the ColdFusion-applications store their fil ... read »
May 15, 2012 at 6:03 PM
Movies As A Religious Experience
@Ben, I don't know whether you'd consider this a religious observation, but it seems to me, in a sense, movies multiply how many lives we get to have. Each movie is like a little extra life we get ... read »