Hack 62. Dynamically View Request Information for XMLHttpRequest
Display the values of environment variables when you make an Ajax request.
It can be useful to know what environment variables are available along with requests made with XMLHttpRequest. In this context, environment variables contain information about the server environment that is associated with a request involving XMLHttpRequest, such as the server name, the querystring, the raw POST data, and the values of various HTTP request headers. (For more on environment variables, see http://en.wikipedia.org/wiki/Environment_variable.) Even if you don't need all this information, it's still cool that you can get a look at it, and Ruby on Rails makes this easy.
This hack displays a textarea on a web page. When the web page launches XMLHttpRequest in response to a button click, the textarea immediately fills up with the environment variable information, without a page rebuild. Figure 7-14 shows the page after the user has clicked the Go Ajax! button. The textarea shows a bunch of useful information, including an HTTP_X_REQUESTED_WITH variable indicating that this was an Ajax-related request.
Figure 7-14. Environment variables accompanying XMLHttpRequest
How Does It Work?
The page, or view, is simple enough. It's just a Rails template that includes some embedded Ruby code:
class HacksController < ApplicationController def index end def show_env if @request.xml_http_request?( ) @headers["Content-Type"] = "text/plain; charset=UTF-8" str=""; @request.env( ).each do |key,value| str+=key.to_s + "==" + value.to_s+"\\n\\n" end render :text => str end end end #end class
First, show_env checks whether the request actually involves XMLHttpRequest (see "Find Out Whether Ajax Is Calling in the Request" [Hack #59]). The action then uses the instance variable @request.env( ) method to iterate through each of the environment variables and store their values. The code then renders this string as the response.
The response text ends up plunked inside the textarea. An important ease-of-use factor with this hack is that you never had to set up or deal at all with the innards of XMLHttpRequest; the Rails method submit_to_remote( ) takes care of that. Sweet!
Hacking the Hack
If the user clicks the Go Ajax! button more than once, the textarea's chunk of data is submitted in the request and ends up as a giant lump inside the RAW_POST_DATA environment variable. To avoid this problem, you can use code to clear the textarea's contents first each time the button is clicked: