[JavaScipt] Cross-Browser HTTP POST Request


This post shows how to make HTTP POST request with query string (key-value pairs) in cross-browser way. The following HTTPPOST function demonstrates how to make such AJAX request:

post.js | repository | view raw
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
/**
 * Cross-browser HTTP POST request
 * @param {string} url The url of HTTP POST request
 * @param {object} keyValuePairs The object which contains data of key-value
 *                 pair(s) to be POSTed. For example, object {'name': 'Bob',
 *                 'age': '21'} represents "name=Bob&age=21".
 * @param {function} callback The callback function if HTTP POST succeeds
 * @param {function} failCallback The callback function if HTTP POST fails
 */
HTTPPOST = function(url, keyValuePairs, callback, failCallback) {
  var xmlhttp;

  if (window.XMLHttpRequest) {
    // code for IE7+, Firefox, Chrome, Opera, Safari
    xmlhttp=new XMLHttpRequest();
  } else {
    // code for IE6, IE5
    xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }

  xmlhttp.onreadystatechange = function() {
    if (xmlhttp.readyState == 4) {
      if (xmlhttp.status == 200)
        callback(xmlhttp.responseText, url);
      else
        failCallback(url);
    }
  };

  xmlhttp.open("POST", url, true);
  xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");

  var kvpairs = '';
  for (var key in keyValuePairs) {
    if (kvpairs == '')
      kvpairs = encodeURIComponent(key) + '=' +
                encodeURIComponent(keyValuePairs[key]);
    else
      kvpairs = kvpairs + '&' + encodeURIComponent(key) + '=' +
                encodeURIComponent(keyValuePairs[key]);
  }

  xmlhttp.send(kvpairs);
};

Usage

usage.js | repository | view raw
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
var url = '/demo/post';
var keyValuePairs = {'name': 'Bob', 'age': '21'};

var callback = function(responseText, url) {
  // write your own handler for success of HTTP POST
  alert('responseText from url ' + url + ':\n'
        + responseText);
};

var failCallback = function(url) {
  // write your own handler for failure of HTTP POST
  alert('fail to post ' + url);
};

HTTPPOST(url, keyValuePairs, callback, failCallback);

Note that you can only make requests in the same domain. To make cross-domain requests, please see reference [1] for more detail. To make cross-browser HTTP GET request, please see reference [2]. To make HTTP POST requests to GAE Python server, see reference [3].


References:

[1]JavaScript Cross-Browser Cross-Domain XMLHttpRequest (XDomainRequest in IE)
[2][JavaScipt] Cross-Browser HTTP GET Request
[3]AJAX Form POST Request to Google App Engine Python
[4]XMLHttpRequest - Web API Interfaces | MDN