<?xml version="1.0" encoding="utf-8"?>
<feed xmlns="http://www.w3.org/2005/Atom" 
      xmlns:thr="http://purl.org/syndication/thread/1.0">
  <link rel="alternate" type="text/html" href="http://www.insideria.com/2009/04/playing-with-jquerys-ajaxsetup.html" />
  <link rel="self" type="application/atom+xml" href="http://www.insideria.com/atom.xml" />
  <id>tag:www.insideria.com,2009://34/tag:www.insideria.com,2009://34.36020-</id>
  <updated>2009-11-16T15:05:41Z</updated>
  <title>Comments for Playing with jQuery&apos;s ajaxSetup Function (http://www.insideria.com/2009/04/playing-with-jquerys-ajaxsetup.html)</title>
  <generator uri="http://www.sixapart.com/movabletype/">Movable Type 4.21-en</generator>
  <entry>
    <id>tag:www.insideria.com,2009://34.36020</id>
    <link rel="alternate" type="text/html" href="http://www.insideria.com/2009/04/playing-with-jquerys-ajaxsetup.html" />
    <link rel="service.edit" type="application/atom+xml" href="http://blogs.oreilly.com/cgi-bin/mt/mt-atom.cgi/weblog/blog_id=34/entry_id=36020" title="Playing with jQuery's ajaxSetup Function" />
    <published>2009-04-22T01:21:47Z</published>
    <updated>2009-04-22T02:02:39Z</updated>
    <title>Playing with jQuery&apos;s ajaxSetup Function</title>
    <summary>A quick look at jQuery&apos;s ajaxSetup feature.</summary>
    <author>
      <name>Raymond Camden</name>
      <uri>http://www.coldfusionjedi.com</uri>
    </author>
    
    <category term="Blogs" />
    
    <content type="html" xml:lang="en" xml:base="http://www.insideria.com/">
      <![CDATA[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.
<p/>
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. 
<p/>

<div class="acode" style="overflow: auto; padding: 10px;" ><div style="overflow-x: visible;">
<code language="perl">
<pre>
$("<span class="quote">#submitBtn</span>").click(<span class="category1">function</span>() {
 	<span class="category1">var</span> value = $("<span class="quote">#number</span>").val()
 	console.<span class="category2">log</span>('<span class="quote">About to run my request...</span>')
 	$.getJSON("<span class="quote">test.cfc?method=double2&amp;returnFormat=json</span>",{number:value},<span class="category1">function</span>(d) {
  		<span class="linecomment">//do nothing with response</span>
  		console.<span class="category2">log</span>('<span class="quote">Done with request, it was </span>'+d)
  	})
})</pre>
</code>

</div></div>
<p/>

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. 
<p/>

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. 
<p/>

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.) 
<p/>

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. 
<p/>

 <div class="acode" style="overflow: auto; padding: 10px;" ><div style="overflow-x: visible;">
<code language="perl">
<pre>
&lt;<span class="category2">html</span>&gt;

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

&lt;body&gt;

&lt;<span class="category2">input</span> <span class="category2">type</span>="<span class="quote">text</span>" id="<span class="quote">number</span>"&gt; &lt;<span class="category2">input</span> <span class="category2">type</span>="<span class="quote">submit</span>" id="<span class="quote">submitBtn</span>" value="<span class="quote">Double</span>"&gt;	
		
&lt;/body&gt;
&lt;/<span class="category2">html</span>&gt;</pre>
</code>

</div></div>
<p/>

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:
<p/>

<a href="http://www.insideria.com/upload/2009/04/Picture%205.png" class="highslide" onclick="return hs.expand(this)"><img src="http://www.insideria.com/upload/2009/04/Picture%205.png" alt="Firebug Report" title="Click to enlarge" width="148"/></a>
<p/>

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. 
<p/>

Ok, one more example. Last night I <a href="http://www.coldfusionjedi.com/index.cfm/2009/4/20/Important-Note-for-ColdFusion-8-Ajax-Developers">blogged</a> 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:
<p/>

<div class="acode" style="overflow: auto; padding: 10px;" ><div style="overflow-x: visible;">
<code language="perl">
<pre>
$.ajaxSetup({
 
 	dataFilter:<span class="category1">function</span>(<span class="category2">data</span>,<span class="category2">type</span>) {
  		<span class="linecomment">//remove "//"</span>
  		console.<span class="category2">log</span>(<span class="category2">data</span>)
  		<span class="category2">data</span> = <span class="category2">data</span>.<span class="category2">substring</span>(2,<span class="category2">data</span>.<span class="category2">length</span>)
  		console.<span class="category2">log</span>(<span class="category2">data</span>)
  		<span class="category1">return</span> <span class="category2">data</span>
  	}
 
})</pre>
</code>

</div></div>
<p/>

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 <b>no</b> 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.
]]>
      
    </content>
  </entry>

  <entry>
    <id>tag:www.insideria.com,2009://34.36020-comment:2058090</id>
    <thr:in-reply-to ref="tag:www.insideria.com,2009://34.36020" type="text/html" href="http://www.insideria.com/2009/04/playing-with-jquerys-ajaxsetup.html"/>
    <link rel="alternate" type="text/html" href="http://www.insideria.com/2009/04/playing-with-jquerys-ajaxsetup.html#comment-2058090" />
    <title>Comment from Alexey on 2009-04-22</title>
    <author>
        <name>Alexey</name>
        <uri>http://nilcolor.com</uri>
    </author>
    <content type="html" xml:lang="en" xml:base="http://nilcolor.com">
        <![CDATA[<p>One more use of $.ajaxSetup I like/use is passing additional parameters to onSuccess function to avoid using globals. Like this:</p>

<pre>
        $.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
        }
</pre>]]>
    </content>
    <published>2009-04-22T07:02:34Z</published>
  </entry>

  <entry>
    <id>tag:www.insideria.com,2009://34.36020-comment:2058095</id>
    <thr:in-reply-to ref="tag:www.insideria.com,2009://34.36020" type="text/html" href="http://www.insideria.com/2009/04/playing-with-jquerys-ajaxsetup.html"/>
    <link rel="alternate" type="text/html" href="http://www.insideria.com/2009/04/playing-with-jquerys-ajaxsetup.html#comment-2058095" />
    <title>Comment from Raymond Camden on 2009-04-22</title>
    <author>
        <name>Raymond Camden</name>
        <uri>http://www.coldfusionjedi.com</uri>
    </author>
    <content type="html" xml:lang="en" xml:base="http://www.coldfusionjedi.com">
        <![CDATA[<p>So wait - am I reading you right? You have a generic object passed in ajaxSetup, and you can use it in the callback. Right?</p>]]>
    </content>
    <published>2009-04-22T11:58:58Z</published>
  </entry>

  <entry>
    <id>tag:www.insideria.com,2009://34.36020-comment:2058162</id>
    <thr:in-reply-to ref="tag:www.insideria.com,2009://34.36020" type="text/html" href="http://www.insideria.com/2009/04/playing-with-jquerys-ajaxsetup.html"/>
    <link rel="alternate" type="text/html" href="http://www.insideria.com/2009/04/playing-with-jquerys-ajaxsetup.html#comment-2058162" />
    <title>Comment from Alexey on 2009-04-23</title>
    <author>
        <name>Alexey</name>
        <uri>http://nilcolor.com</uri>
    </author>
    <content type="html" xml:lang="en" xml:base="http://nilcolor.com">
        <![CDATA[<p>Yep. You are right.</p>]]>
    </content>
    <published>2009-04-23T13:03:05Z</published>
  </entry>

  <entry>
    <id>tag:www.insideria.com,2009://34.36020-comment:2058479</id>
    <thr:in-reply-to ref="tag:www.insideria.com,2009://34.36020" type="text/html" href="http://www.insideria.com/2009/04/playing-with-jquerys-ajaxsetup.html"/>
    <link rel="alternate" type="text/html" href="http://www.insideria.com/2009/04/playing-with-jquerys-ajaxsetup.html#comment-2058479" />
    <title>Comment from Robert - greepit.com on 2009-04-28</title>
    <author>
        <name>Robert - greepit.com</name>
        <uri>http://www.greepit.com</uri>
    </author>
    <content type="html" xml:lang="en" xml:base="http://www.greepit.com">
        <![CDATA[<p>nice tut.</p>]]>
    </content>
    <published>2009-04-28T10:35:51Z</published>
  </entry>

</feed
