Home  >  

Playing with jQuery's ajaxSetup Function

Author photo
AddThis Social Bookmark Button
A few weeks ago I discovered jQuery had an ajaxSetup feature. As you may be able to guess, this feature let's you set certain defaults for your Ajax operations. At the time, I really wasn't sure why you would use it. For example, what would be the point of defaulting the URL? Normally if I have N Ajax based requests on a page, each one has a unique URL. Of course, like most things in life, it takes a real life need to drive home the point of features like this. Here are two examples that recently came up where the ajaxSetup feature was a perfect fit.

First, how can we handle displaying a "Loading..." message before firing off Ajax requests? And with that - how can we clear the message when done? It isn't too difficult to do within the method itself.

$("#submitBtn").click(function() {
 	var value = $("#number").val()
 	console.log('About to run my request...')
 	$.getJSON("test.cfc?method=double2&returnFormat=json",{number:value},function(d) {
  		//do nothing with response
  		console.log('Done with request, it was '+d)
  	})
})

I've got a simple method here tied to a submit button's click action. Before the getJSON Ajax event is fire I log to the console. (Normally this would be a browser visible loading text or graphic, etc.) In the callback function, when the request is done, I use another console.log. Easy enough - a message both before and after. However, if we have a large number of actions like this on a page, it may be nice to abstract that out.

Looking at the docs for ajaxSetup I found two methods I thought made sense. The first was beforeSend. Technically it is meant to manipulate the XHMLHttpRequest before sending it out. But it seemed like a good place to handle my 'pre-send' operation.

The next method I found was complete. As you can guess, it will run when the Ajax function is complete, but even cooler, complete will run after either a successful call or a call that throws an error. It kinds of acts like Finally in a Java Try/Catch block. (And frankly, error handling is something I am not yet doing well in my Ajax applications. I need to think about that more and help error-proof my applications.)

Given that we can define these two functions at a global level in jQuery, my concern was how they would impact my existing code. I assumed it would do nothing to code right before my call, but what about my callback? Would it overwrite the call back? And if not, would it run before or after my callback? I whipped up a quick test to see.

<html>

<head>
<script src="jquery/jquery.js"></script>
<script>
$(document).ready(function() {
 	
 	$.ajaxSetup({
  
  		beforeSend:function(req) {
   			console.log('GLOBAL:beforeSend')
   		},
  
  		complete:function(req) {
   			console.log('GLOBAL:complete')
   		}
  
  
  	})
 	
 	$("#submitBtn").click(function() {
  		var value = $("#number").val()
  		console.log('About to run my request...')
  		$.getJSON("test.cfc?method=double&returnFormat=json",{number:value},function(d) {
   			//do nothing with response
   			console.log('Done with request')
   		})
  	})
 	
})
</script>
</head>

<body>

<input type="text" id="number"> <input type="submit" id="submitBtn" value="Double">	
		
</body>
</html>

Nothing in here is too terribly complex. My ajaxSetup object is simple. I've got beforeSend and complete defined. Notice the console.log messages. The click function has my 'old' code with console.log messages defined in there already. When run, here is how Firebug reported it:

Firebug Report

No big surprise here. My function's console.log ran first. Then the global beforeSend. Next my callback ran, and when it was done, the global complete ran. I guess this is expected, but it was nice to see it confirmed, and the docs had not made it very clear to me.

Ok, one more example. Last night I blogged a warning to ColdFusion/Ajax developers. ColdFusion has an Ajax security feature by which JSON requests are prefixed with a string, like //. While this works great with ColdFusion's builtin front-end Ajax stuff, it doesn't play well with jQuery and other libraries. While it is easy enough to disable the prefix on the server side, jQuery provides a cool way to handle it as well in the ajaxSetup object. By using the dataFilter function, you can remove the prefix yourself. Consider:

$.ajaxSetup({
 
 	dataFilter:function(data,type) {
  		//remove "//"
  		console.log(data)
  		data = data.substring(2,data.length)
  		console.log(data)
  		return data
  	}
 
})

Ignoring the declarations and console.log lines, it's really just two lines of code. One line is used to get the substring from the result. I probably should double check to see that the prefix is there first, but, it works. The second important line just returns the data. What's cool is - I could have added this to my code after discovering that the prefix was added to the server. There is no no need to even touch the original code. On a page with 10+ Ajax requests, I could do this one time to correct the JSON results for all the calls. Awesome.

Read more from Raymond Camden. Raymond Camden's Atom feed cfjedimaster on Twitter

Comments

4 Comments

Alexey said:

One more use of $.ajaxSetup I like/use is passing additional parameters to onSuccess function to avoid using globals. Like this:

        $.ajaxSetup({'_tc':{contID:_id, domID:'c'+_id}});
        $.getJSON('/crm/contact/'+_id, function(data){
            var $cont = $('#'+this._tc.domID);
            // notice that this._tc is an object we created with
            // ajaxSetup and assign to XHTTPRequest object
            // (which is `this` here)
            
            // other processing code
        }
Raymond Camden said:

So wait - am I reading you right? You have a generic object passed in ajaxSetup, and you can use it in the callback. Right?

Alexey said:

Yep. You are right.

Robert - greepit.com said:

nice tut.

Leave a comment


Tag Cloud

iPad

What's your take on the iPad? (Putting aside the Flash/iPad flame war)

Answer

Latest Features

Recommended for You

@InsideRIA on Twitter

Archives

  • Or, visit our complete archive.  

About This Site

Welcome to the premiere community site for all things RIA sponsored by O'Reilly Media and Adobe Systems Incorporated.