Hi

Ive been using some httpRequests but have gotten tired of writing the 'preparation code' for every request... so I thought I'd make a function that accepted a URL, and a list of parameters and would return the responseText variable...

But what seems to happen is that my other code continues without the ajaz call being completed... and so if I perform an operation on that responseText variable, it shows as 'undefined'...

I thought if I adjusted my ajaz function to accept a function name as well which would operate on the responseText, it would solve the problem... I think Ive seen someone pass a function as an argument before... is that possible? Or is there a uniform solution for avoiding writing ajax code...? my ajaxCall function is below:

function ajaxCall(path,querystring){
//new http request object
	var http;
	http=GetXmlHttpObject();//use another function to create the correct object
	var url = path;
	var params = querystring;
	http.open("POST", url, true);
	
	//Send the proper header information along with the request
	http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
	http.setRequestHeader("Content-length", params.length);
	http.setRequestHeader("Connection", "close");
	
	http.onreadystatechange = function() {
		if(http.readyState == 4 && http.status == 200) {
                     return http.responseText;
		}
	}
	http.send(params);
}

var returnContent = ajaxCall('www.mysite.com/userdetails.php','name=John&surname=Smith');

Recommended Answers

All 2 Replies

Lifeworks,

In Javascript, you can indeed pass a function, both as an argument or as a returned result. This is because Javascript functions are "first-class objects" (see here for example).

A more typical ajax caller might look something like this:

function ajaxCall(url, successFn, failFn) {
	var httpRequest = GetXmlHttpObject();
	if(!httpRequest) {
		failFn();
		return false;
	}
	httpRequest.open("GET", url, true);
	httpRequest.onreadystatechange = function() {
		if(httpRequest.readyState == 4) {
			if(httpRequest.status == 200) { successFn(httpRequest.responseText); }
			else { failFn(); }
		}
	}
	http.send(null);
	return true;
}

And it might be called with something like this:

var x = ajaxCall('www.mysite.com/userdetails.php?name=John&surname=Smith',
	function(responseText){
		//Handle response here
		//...
	},
	function(){
		//Handle failure here
		//...
	}
);
if(!x){
	//Alternative (non-AJAX) course of action
	//...
}

This is neither tested nor definitive. An infinite number of possibilities exists.

One thing to note is that there's no point returning values from the success/failure handlers as there's nothing (in this pattern) to return them to.

Here's something very similar for fetching and interpreting a JSON response, from a project I'm currently working on:

function fetchJSON(params, reviverFn, postRevivalFn, failFn){
	if(!params || typeof params !== 'object' || typeof params.url == 'undefined') { return; }
	if(typeof params.type === 'undefined') { params.type = ''; }
	if(!reviverFn) { reviverFn = function(){}; }
	if(!postRevivalFn) { postRevivalFn = function(){}; }
	if(!failFn) { failFn = function(){}; }
	var xmlhttp = AJAX.GetXmlHttpObject();
	if(!xmlhttp){ return; }
	xmlhttp.open("GET", params.url, true);
	xmlhttp.onreadystatechange = function(){
		if(xmlhttp.readyState == 4){
			if(xmlhttp.status == 200){
				var jsonObj = JSON.parse( xmlhttp.responseText, reviverFn );//call to JSON lib
				postRevivalFn(xmlhttp.responseText, jsonObj);
			}
			else{
				failFn(params.type + ': Failed to get data');
			}
		}
	}
	xmlhttp.send(null);
	return true;
}

In this case, our revivier function will return a value or null/undefined, because of the way JSON.parse works.

Airshow

Airshow, you legend!

Thanks very much, this is exactly what I was looking for, havent experimented much with json requests yet, but that ajaxCall will save me a ton of unneccesary code and time!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.