dans.blog


The miscellaneous ramblings and thoughts of Dan G. Switzer, II

ColdFusion UDF for detecting jQuery AJAX operations…

Raymond Camden justed posted an article on detecting jQuery AJAX operation using ColdFusion. I honor of that post, I thought I'd share the UDF I've been using in my application for quite some time:

<cffunction name="isAjaxRequest" output="false" returntype="boolean" access="public">
    <cfset var headers = getHttpRequestData().headers />
    <cfreturn structKeyExists(headers, "X-Requested-With") and (headers["X-Requested-With"] eq "XMLHttpRequest") />
</cffunction>

The code uses the exact same logic the technique in Raymond's post, but having the code in a function makes your detection code a lot easier to read.

Now when you want to detect if a request came from an AJAX operation, you can just do:

<cfif isAjaxRequest()>
    Came from jQuery! :)
<cfelse>
    Didn't come from jQuery. :(
</cfif>

Doesn't get any easier than that!