zorin-e
6/27/2017 - 3:07 PM

Ajax with promise

Ajax with promise

;(function() {
	this.Ajax = function() {
		var defaults = {
			method: 'get',
			url: null,
			data: null,
			async: true,
			type: 'form',
			convData: false // set true, if data is an object and type on default
		}

		this.options = extendDefaults(defaults, arguments[0] || {});

		if(this.options.url === null) {
			throw new Error('url is not defined');
		}
	}

	/**
	 *
	 * private methods
	 *
	 */
	
	function extendDefaults(source, properties) {
		for(var prop in properties) {
			if(properties.hasOwnProperty(prop)) {
				source[prop] = properties[prop];
			}
		}

		return source;
	}

	function reqData(req) {
		switch(this.options.method.toLowerCase()) {
			case 'post':
				req.send(this.options.data);
				break;
			case 'get':
				req.send();
				break;
		}
	}

	function encData() {
		var string = '';
			
		for (var i = this.options.data.split('&').length - 1; i >= 0; i--) {
			var val = data[i].split('=');
			string += val[0] + '=' +encodeURIComponent(val[1]);
		}

		return string;	
	}


	/**
	 *
	 * public methods
	 *
	 */

	Ajax.prototype = {
		send: function() {
			var self = this;

			return new Promise(function(resolve, reject) {
				var req, data, getUrl;

				req = new XMLHttpRequest();

				// get url
				getUrl = 
					self.options.method.toLowerCase() === 'get' && self.options.data ? 
						self.options.url + encData.call(self)
						:
						self.options.url;
				
				// if data is an object and type on default
				if(self.options.method.toLowerCase() === 'post' && 
					typeof self.options.data === 'object' &&
					self.options.convData === true
				) {
					self.options.data = encData.call(self);
				}

				// open connection
				req.open(self.options.method, getUrl, self.options.async);

				req.onload = function() {
					if(req.status === 200) {
						resolve(req.response)
					}
					else {
						reject(Error(req.statusText));
					}
				}

				req.onerror = function() {
					reject(Error('Network error'));
				}

				// set headers
				if(self.options.type.toLowerCase() === 'json') {
					req.setRequestHeader('Content-Type', 'application/json');					
				}
				else if(self.options.type.toLowerCase() === 'form') {
					req.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
				}

				// send request
				reqData.call(self, req);
			});
		}
	}
}());
var ajax = new Ajax({
    url: '/public/static/js/weblogic/fake-jackpots-data.json',
    method: 'post',
    type: 'json',
    data: JSON.stringify({search: 'some value'})
});

ajax.send()
    .then(
      // preloader show
    )
    .then(JSON.parse)
    .then(function(data) {
        console.log('ok', data);
    })
    .catch(function(error) {
        console.log('Can\'t load the data');
    })
    .then(function() {
      // preloader hide
    });