Simple Ajax by Jeff Manning | JavaScriptSource

Simple Ajax by Jeff Manning

Jeff Manning Jun 13, 2012

Abstract

A simple script that simplifies Ajax requests

Description

An ajax script that supports both get, and post protocols that allows users to create diverse ajax applications using a simpler set of functions createRequest() allows you to create a request to the page addParam() - adds a parameter to the request sendRequest() accepts a string to be executed using eval, and an optional parameter setting the type of request to post. This function then sends the request.

Code Snippet

var xmlhttp;
var response = null;
var variables = "";
var page;
var useAmp = false;
function createRequest(url) {
	if (window.XMLHttpRequest) {
		// code for IE7+, Firefox, Chrome, Opera, Safari
		xmlhttp=new XMLHttpRequest();
	}
	else // code for IE6, IE5
		xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
	page = url;
}

function addParam(name,value) {
	if(useAmp == true)
		variables += "&";
	variables += escape(name) + "=" + escape(value)
	useAmp = true;
}

function sendRequest(instructions,type) {
	//the instructions param takes the form of an eval statement
	if(type == null) {
		page += "?" + variables
		xmlhttp.open("GET", page, true);
			xmlhttp.onreadystatechange=function() {
			if (xmlhttp.readyState==4 && xmlhttp.status==200) {
				response=xmlhttp.responseText;
				eval(instructions)
			}
		}
		xmlhttp.send();

	}
	else {
		xmlhttp.open("POST", page, true);
		//Send the proper header information along with the request
		xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
		xmlhttp.setRequestHeader("Content-length", variables.length);
		xmlhttp.setRequestHeader("Connection", "close");
			xmlhttp.onreadystatechange=function() {
			if (xmlhttp.readyState==4 && xmlhttp.status==200) {
				response=xmlhttp.responseText;
				eval(instructions)
			}
		}
		xmlhttp.send(variables);
	}


}

Leave a Response

(1 comment)

I need to do a program where the example they seamlessly blend with jQuery javascript, and do not want to give the dns, it takes as a parameter in the sdk

Danilo Aug 13, 2012