Jump to content

Universal AJAX script


gamesmstr

Recommended Posts

While doing some late night developing, I got very tired of having to write a new ajax script for every new condition I had in a page, so I decided to see what I could do about making 1 function to handle any data I wanted to pass.  And so I did.  It worked so well, I thought I'd share here and see if any of you could 1) improve it or 2) use it.

 

The format to call it is: AJAX(TargetContainer,Filename,Variable1+variable2+...,FormField1+FormField2+...)

 

Take a look and let me know what you think.

 

<script type="text/javascript">
function createXMLHttpRequest() {
	if (typeof XMLHttpRequest != 'undefined') { 
		return new XMLHttpRequest(); 
	} 
	try { 
		return new ActiveXObject("Msxml2.XMLHTTP"); 
	} catch (e) {
			try { 
				return new ActiveXObject("Microsoft.XMLHTTP"); 
			} catch (e) {}
	}
	return false; 
}	

function AJAX(target,filename,vars,fields) {
	var maindiv = createXMLHttpRequest();
	var params = '';
	if (vars != ''){
		var varval=vars.split("+");
		for(var i = 0;i < varval.length;i++){
			if (params == ''){
				params=params + "varval" + i + "=" + varval[i];
			} else {
				params=params + "&varval" + i + "=" + varval[i];
			}
		}
	}
	if (fields != ''){
		var field=fields.split("+");
		var fieldval=new Array(field.length);
		for(var i = 0;i < field.length;i++){
			fieldval[i]=document.getElementById(field[i]).value;
			if (params == ''){
				params=params + "fieldval" + i + "=" + fieldval[i];
			} else {
				params=params + "&fieldval" + i + "=" + fieldval[i];
			}
		}
	}
	maindiv.open("POST",filename, true);
	maindiv.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
	maindiv.onreadystatechange = function() {
		if(maindiv.readyState == 4 && maindiv.status == 200) {
			document.getElementById(target).innerHTML = maindiv.responseText;
			refresh_stats();
		}
	}
	maindiv.send(params);
}
</script>

 

If anyone wants to use it, feel free!  Just credit me.  :P

 

Gabriel Pettit

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.