Icontem

File: serverlink.js

Recommend this page to a friend!
  Classes of Chris Jeffries  >  Web JSON Editor  >  serverlink.js  >  Download  
File: serverlink.js
Role: Auxiliary script
Content type: text/plain
Description: JS to promisify XMLHttp
Class: Web JSON Editor
Create data values in JSON format interactively
Author: By
Last change:
Date: 1 year ago
Size: 4,454 bytes
 

Contents

Class file image Download
/***
 * Utility functions for interacting with a server
 * 
 * Usage
 *  docLoad(parmsObject).then(function(response){
 *  	<doStuffAfterDocIsFullyLoaded using parmsObject>;
 *  });
 * 	getData(<servername>,<JsObjectTodespatch>).then(function(JsObjectAsResponse) {
 * 		<codeToDoSomethingWithTheresponse>;
 *  });
 * 	getrawData(<servername>,<dataTodespatch>).then(function(response) {
 * 		<codeToDoSomethingWithTheresponse>;
 *  });
 ***/


/***
 * docload() - wait until document loaded before invoking '.then'
 * 
 * @param mixed parms values to be passed to the .then process
 ***/
	function docLoad(parms)
	{
		if(parms == undefined) parms = {};
		
		let p = new Promise( function (resolve, reject) {
			window.addEventListener('load',  function( ) { resolve(parms);});
			window.addEventListener('error', function(e) { reject (e);});
		});
		return p;
	}

/***
 * getData() - promise to retrieve data from a URL	
 * 
 * Designed specifically to work with JSONServer.class.php. Expects a
 * specification of what is required as a Javascript object and returns
 * the server response as a Javascript object to the function specified
 * in the .then method.
 * 
 * @param   text url 		The location of the server (typically server.php)
 * @param   json request	A request which must conform to the expectations of
 *                      	JSONServer.class.php
 * @resolve json 			A response object as served by JSONServer.class.php
 * @reject  json			A response object as served by 
 * 							JSONServer.class.php or by getData itself 
 * 							(e.g. if a transmission failure)
 ***/
	function getData(url, request)
	{
		let key, requesttype, p, k
		
		requesttype = 's'
		if(request instanceof Array) {
			requesttype = 'a';
		} else {
			for(key in request)	{
				if (request[key] instanceof Object) {
					requesttype = 'o';
				}
				break;
			}
		}
		
		p = new Promise( function (resolve, reject){
			//retrieve data from server based on a spec using json format
			let xhttp = new XMLHttpRequest();
		
			xhttp.onreadystatechange = function() {
				if (this.readyState == 4) {
					if (this.status == 200) {
						let response = JSON.parse(xhttp.responseText);
						if (requesttype == 's') {
							if (response.severity == 0) {
								resolve(response)
							} else {
								reject(response);
							}
						}
						else
						{
							let severity = 0;
							if(requesttype == 'a') {
								for (k=0; k<response.length; k++)
								{
									if (response[k].severity > severity)
										severity = response[k].severity;
								}
							} else {
								let keys = getkeys(response)
								for (key in keys)
								{
									if (response[k].severity > severity)
										severity = response[k].severity;
								}
							}
							response.severity = severity;
							if (severity > 0)
								reject(response);
							else
								resolve(response);
						}
					} else {
						let response = {};
						response.resultData = {};
						response.errorMessage = 'XHTTP:'+ this.status + ":" + xhttp.responseText, 
						response.errorNum = 'CLIENT_1';
						response.severity = 2;
						reject(response);
					}
				} 
			};
			xhttp.open("POST", url, true);
			xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
			xhttp.send('data='+JSON.stringify(request));
		});
		return p;
	}
	
/***
 * getRawData() - promise to retrieve data from a URL	
 * 
 * Send an XMLHTTP request and wait for a response. Uses POST.
 * Returns the server response to the .then function
 * in the .then method.
 * 
 * @param   text url 		The location of the server/page
 * @param   text request	in the form parm1=value1&parm2=value2...
 * @resolve text 			The response from the server
 * @reject  json			A response object as served by 
 * 							getRawData (e.g. if a transmission failure)
 ***/	
	function getRawData(url, data) 	//send the pre processed data to url and
								// releases the responseText when it is resolved
	{
		let p = new Promise( function (resolve, reject){
			//retrieve data from server
			let xhttp = new XMLHttpRequest();
		
			xhttp.onreadystatechange = function() {
				if (this.readyState == 4) {
					if (this.status == 200) {
						resolve(xhttp.responseText);
					} else {
						reject('XHTTP:'+ this.status);
					}
				} 
			};
			xhttp.open("POST", url, true);
			xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
			xhttp.send('data='+data);
		});
		return p;
	}