1<!DOCTYPE html>
2<!--
3Copyright 2015 The Chromium Authors. All rights reserved.
4Use of this source code is governed by a BSD-style license that can be
5found in the LICENSE file.
6-->
7
8<script>
9'use strict';
10
11var simple_xhr = (function() {
12
13  var LOGIN_ERROR_MESSAGE = 'Please check if you are logged in with a ' +
14                            'google.com or chromium.org account in the ' +
15                            'upper right corner of the page.';
16
17  var handleError_ = function(request, callback) {
18    callback(LOGIN_ERROR_MESSAGE);
19  };
20
21  // For abort request, error callback is called without message.
22  var handleAbort_ = function(request, callback) {
23    callback(null);
24  };
25
26  var handleLoad_ = function(request, loadCallback, errorCallback) {
27    if (request.status != 200) {
28      errorCallback('HTTP error ' + request.status);
29      return;
30    }
31    try {
32      var response = JSON.parse(request.responseText);
33    } catch (e) {
34      errorCallback(LOGIN_ERROR_MESSAGE);
35      return;
36    }
37    if (response.error) {
38      errorCallback(response.error);
39      return;
40    }
41    loadCallback(response);
42  };
43
44  var paramString_ = function(params) {
45    var strings = [];
46    for (var name in params) {
47      strings.push(name + '=' + encodeURIComponent(params[name]));
48    }
49    return strings.join('&');
50  };
51
52  var send = function(url, params, loadCallback, errorCallback) {
53    var postdata = paramString_(params);
54    var request = new XMLHttpRequest();
55    request.onerror = handleError_.bind(this, request, errorCallback);
56    request.onabort = handleAbort_.bind(this, request, errorCallback);
57    request.onload = handleLoad_.bind(
58        this, request, loadCallback, errorCallback);
59    request.open('post', url, true);
60    request.setRequestHeader(
61        'Content-type', 'application/x-www-form-urlencoded');
62    request.send(postdata);
63    return request;
64  };
65
66  return {
67    send: send
68  };
69})();
70
71</script>
72