src code

class Ajax.Request

Description

Initiates and processes an Ajax request.

Ajax.Request is a general-purpose class for making HTTP requests.

Automatic JavaScript response evaluation

If an Ajax request follows the same-origin policy and its response has a JavaScript-related Content-type, the content of the responseText property will automatically be passed to eval.

In other words: you don't even need to provide a callback to leverage pure-JavaScript Ajax responses. This is the convention that drives Rails's RJS.

The list of JavaScript-related MIME-types handled by Prototype is:

  • application/ecmascript
  • application/javascript
  • application/x-ecmascript
  • application/x-javascript
  • text/ecmascript
  • text/javascript
  • text/x-ecmascript
  • text/x-javascript

The MIME-type string is examined in a case-insensitive manner.

Methods you may find useful

Instances of the Request object provide several methods that can come in handy in your callback functions, especially once the request is complete.

Is the response a successful one?

The Ajax.Request#success method examines the XHR object's status property and follows general HTTP guidelines: unknown status is deemed successful, as is the whole 2xy status code family. It's a generally better way of testing your response than the usual 200 == transport.status.

Getting HTTP response headers

While you can obtain response headers from the XHR object using its getResponseHeader method, this makes for verbose code, and several implementations raise an exception when the header is not found. To make this easier, you can use the Ajax.Response#getHeader method, which delegates to the longer version and returns null if an exception occurs:

new Ajax.Request('/your/url', {
  onSuccess: function(response) {
    // Note how we brace against null values
    if ((response.getHeader('Server') || '').match(/Apache/))
      ++gApacheCount;
    // Remainder of the code
  }
});
Evaluating JSON headers

Some backends will return JSON not as response text, but in the X-JSON header. In this case, you don't even need to evaluate the returned JSON yourself, as Prototype automatically does so. It passes the result as the headerJSON property of the Ajax.Response object. Note that if there is no such header — or its contents are invalid — headerJSON will be set to null.

new Ajax.Request('/your/url', {
  onSuccess: function(transport) {
    transport.headerJSON
  }
});

Constructor

Instance methods