Connect with:
About Me
Alessandro Annini
I'm a freelance developer currently working at Leaff.it/ I really love famo.us framework and its amazing potential and if you're like me, and you want the web to win, please share some snippet of code for the community and grow faster with us
Categories
Meta
Famo.us Code | Simple server request via XHR2
171
post-template-default,single,single-post,postid-171,single-format-standard,ajax_updown_fade,page_not_loaded,,qode-theme-ver-6.2.1

Simple server request via XHR2

23 Jun Simple server request via XHR2

You can use it in Famo.us directly by require.

[Thanks to LeXXik]

 

This is a simple XHR2 helper module for Famo.us framework.

req.get({ url: '/user/me' }).then(function(response) {
    // handle response
});

Getting Started

Dependency:

AjaxRequest is using asynchronous requests and requires Q by Kris Kowal.

  • Add Q library in your HTML header, before you load Famo.us. For example:
<script type="text/javascript" src="q.js"></script>
<script type="text/javascript" src="https://famo.us/lib/alameda.min.js"></script>
<script type="text/javascript" src="http://code.famo.us/famous/0.2/famous.min.js"></script>

 

How to load

  • Pull in with require(AjaxRequest);
  • Create a new instance by passing options to AjaxRequest methods. Any passed options will override the defaults.

Supported methods

.get(options)
.post(options)  // request method overrides to 'POST'

 

Default Options

{
    method: 'GET',
    url:    undefined,
    type:   'application/json',
    params: undefined,
    timeout: 5000       // ms, before request times out
}

Examples

var ajaxRequest = require('AjaxRequest');

var req = new ajaxRequest();
req.get({ url: '/user/me' }).then(function(response) {
    // handle server response
    console.log(response);
}).catch(function(err) { console.log(err); }).done();
var ajaxRequest = require('AjaxRequest');

var req = new ajaxRequest();
var user = {
    username: 'James',
    password: 'Bond'
};
req.post({ 
    url: '/auth/login',
    params: user,
    timeout: 10000
}).then(function(response) {
    // handle server response
    console.log(response);
}).catch(function(err) { console.log(err); }).done();

 

 ALL THE CODE

define(function(require, exports, module) {
    var OptionsManager  = require('famous/core/OptionsManager');

    function AjaxRequest() {

        this.response = Q.defer();
        this.options = Object.create(AjaxRequest.DEFAULT_OPTIONS);
        this._optionsManager = new OptionsManager(this.options);
    };

    AjaxRequest.DEFAULT_OPTIONS = {
        method: 'GET',
        url: undefined,
        type: 'application/json',
        params: undefined,
        timeout: 5000
    };

    AjaxRequest.prototype.get = function get(options) {
        _makeRequest.call(this, options);
        return this.response.promise;
    };

    AjaxRequest.prototype.post = function post(options) {
        _makeRequest.call(this, options);
        return this.response.promise;
    };

    // make your own helper methods!
    // AjaxRequest.prototype.loginRequest = function loginRequest(options) {
    //     this.options.method = 'POST';
    //     this.options.url = '/auth/login';
    //     _makeRequest.call(this, options);
    //     return this.response.promise;
    // };

    function _makeRequest(options) {

        this._optionsManager.setOptions(options);

        if (window.XMLHttpRequest) { // Mozilla, Safari, ...
            var req = new XMLHttpRequest();
        } else if (window.ActiveXObject) { // IE
            try {
                var req = new ActiveXObject("Msxml2.XMLHTTP");
            } catch (e) {
                try {
                    var req = new ActiveXObject("Microsoft.XMLHTTP");
                } catch (e) {};
            };
        };

        if (!req) {
            console.log('Unable to create an XMLHTTP instance');
            return false;
        };

        // .open(method, url, async)
        req.open(this.options.method, this.options.url, true);

        var ctx = this;
        req.onreadystatechange = function() {
            try {
                if (req.readyState === 4) {
                    if (req.status) {
                        ctx.response.resolve(req);
                    } else {
                        ctx.response.reject("HTTP " + req.status + " for " + ctx.options.url);
                    };   
                };
            } catch (e) {
                console.log('Exception: ' + e.description);
            };
        };
        req.setRequestHeader('Content-Type', this.options.type);
        this.options.timeout && setTimeout(this.response.reject, this.options.timeout);
        if (this.options.params) {
            if (this.options.type === 'application/json') {
                req.send(JSON.stringify(this.options.params));
            } else {
                req.send(this.options.params);
            };
        } else req.send();
    };

    module.exports = AjaxRequest;
});
XHR2 Request