back to Overview

$.request()

Initiates a HTTP request to the given URL, using XMLHttpRequest.
Web module only.

Syntax Variants

$.request(method, url)
$.request(method, url, data)
$.request(method, url, data, settings)

Parameters

method
the HTTP method, e.g. 'get', 'post' or 'head' (rule of thumb: use 'post' for requests that change data on the server, and 'get' to request data). Not case sensitive.
url
the server URL to request. May be a relative URL (relative to the document) or an absolute URL. Note that unless you do something fancy on the server (keyword to google: Access-Control-Allow-Origin), you can only call URLs on the server your script originates from.
data (optional)
data to send in the request, either as POST body or as URL parameters. It can be either a plain object as map of parameters (for all HTTP methods), a string (for all HTTP methods), a DOM document ('post' only) or a FormData object ('post' only). If the method is 'post', it will be sent as body, otherwise parameters are appended to the URL. In order to send several parameters with the same name, use an array of values in the map. Use null as value for a parameter without value.
settings (optional)
a map of additional parameters. Supports the following properties (all optional):
headers
a map of HTTP headers to add to the request. Note that you should use the proper capitalization for the header 'Content-Type', if you set it, because otherwise it may be overwritten.
xhr
a map of properties to set in the XMLHttpRequest object before the request is sent, for example {withCredentials: true}.
user
username for HTTP authentication, together with the pass parameter
pass
password for HTTP authentication, together with the user parameter
(return value)
a Promise containing the request's status. If the request has successfully completed with a HTTP status 2xx, the promise's completion handler will be called as function(text, xhr):
text
The response sent by the server as text.
xhr
The XMLHttpRequest used for the request. This allows you to retrieve the response in different formats (e.g. responseXml for an XML document), to retrieve headers and more.
The failure handler will be called as function(statusCode, statusText, text):
statusCode
The HTTP status (never 200; 0 if no HTTP request took place).
text
The response's body text, if there was any, or the exception as string if the browser threw one.
xhr
The XMLHttpRequest used for the request. This allows you to retrieve the response in different formats (e.g. responseXml for an XML document), to retrieve headers and more..
The returned promise supports stop(). Calling stop() will invoke the XHR's abort() method. The underlying XmlHttpRequest can also be obtained from the promise's xhr property.

Description

Initiates a HTTP request to the given URL, using XMLHttpRequest. It returns a Promise object that allows you to obtain the result.

Example

Invokes a REST web service and parses the resulting document using JSON:

$.request('get', 'http://service.example.com/weather', {zipcode: 90210})
   .then(function(txt) {
        var json = $.parseJSON(txt);
        $('#weatherResult').fill('Today's forecast is is: ' + json.today.forecast);
   })
   .error(function(status, statusText, responseText) {
        $('#weatherResult').fill('The weather service was not available.');
   });

Example

Sending a JSON object to a REST web service:

var myRequest = {         // create a request object that can be serialized via JSON
     request: 'register',
     entries: [
       {name: 'Joe',
     	    job: 'Plumber'
       }
     ]};

function failureHandler() {
  $('#registrationResult').fill('Registration failed');
}

$.request('post', 'http://service.example.com/directory', $.toJSON(myRequest))
    .then(function(txt) {
       if (txt == 'OK')
            $('#registrationResult').fill('Registration succeeded');
       else
             failureHandler();
       })
    .error(failureHandler);

Example

Using HTTP authentication and a custom XMLHttpRequest property.

var handler = $.request('get', 'http://service.example.com/userinfo', null, {xhr: {withCredentials: true}, user: 'me', pass: 'secret'});

See also..

  • values() serializes an HTML form in a format ready to be sent by $.request.
  • $.parseJSON() can be used to parse JSON responses.
  • $.toJSON() can create JSON messages.
  • _.format() can be useful for creating REST-like URLs, if you use JavaScript's built-in escape() function.

Comments

comments powered by Disqus

back to Overview

Functions