gamesmstr Posted September 16, 2010 Share Posted September 16, 2010 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. Gabriel Pettit Quote Link to comment https://forums.phpfreaks.com/topic/213537-universal-ajax-script/ Share on other sites More sharing options...
gamesmstr Posted September 16, 2010 Author Share Posted September 16, 2010 I forgot to mention something. The variables passed will be varval0, varval1,... and the field values will be fieldval0,fieldval1,... just use the $_POST method to retrieve them. Quote Link to comment https://forums.phpfreaks.com/topic/213537-universal-ajax-script/#findComment-1111551 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.