Not yet rated

Problem

Many popular JavaScript libraries (jQuery, Prototype, YUI, Mootools, etc) pass in a special HTTP header of "X-Requested-With" with all AJAX calls.

Solution

Use the getHttpRequestData() function to retrieve all the data sent from the client in the HTTP request to look for special headers that indicate an AJAX request.

Detailed explanation

Since most common JavaScript libraries send the custom "X-Requested-With" HTTP header with all AJAX calls, you can use the following UDF to determine if the current request was made via AJAX:

<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>

You can now check to see if the current request was made via AJAX:

<cfif isAjaxRequest()>
    Came from an AJAX call!
<cfelse>
    Did not come from an AJAX call. :(
</cfif>

+
This work is licensed under a Creative Commons Attribution-Noncommercial-Share Alike 3.0 Unported License. Permissions beyond the scope of this license, pertaining to the examples of code included within this work are available at Adobe.

Report abuse

Related recipes