This business with the [] and radio buttons appears to be a red herring, or a holdover form some previous syntax no longer required. When a form submits, if there is a radio group, only the one (if any) that is checkd is passed, regardless of whether or not the [] is appended to the name used by the group. With a checkbox, its name/value pair is only sent if it is checked. I've updated the script to act like that.
Anyways, I'm almost done (never really done). I just have to add callbacks for various results/readyStates other than success, and perhaps a hook for optional use of json in interpreting the responseText. I've added some new features. Most notable is the loadXmlHttp.attachForm() function. It allows you to attach loadXmlHttp to a form with a single call in or linked to the head.
Another thing worthy of mention, is that if using the default callback, you may now choose to have your responseText appended (optionally with HTML or a string added in front of it, use an empty string '' if nothing should be added) to the target element, rather than replace it's content.
All changes are documented at the beginning of the script. There are also expanded descriptions of some of the features already included:
Code:
/* loadXmlHttp Script ©2009 John Davenport Scheuer
as first seen in http://www.dynamicdrive.com/forums/
username: jscheuer1 - This Notice Must Remain for Legal Use
*/
/* reqObject Properties - //all optional, comma delimit
url: page_to_fetch //defaults to this page
method: POST_or_GET //defaults to GET
el: element_to_populate //defaults to none, overrides id
id: id_of_element_to_populate //defaults to none, requires no el
append: quoted_HTML_or_String //if populating via the default callback, this will be appended along with the responseText
form: form_or_name_of_or_number_of_form_submitting_data //defaults to none, requires method: 'POST' or no query
data: encoded_data_to_send_with_POST_request //defaults to none, requires POST and no form
query: encoded_data_to_send_with_GET_request //defaults to none, requires GET, overrides form
callback: function_to_run_on_readyStateChange //defaults to populate on success, in default mode requires el or id
bust: true_OR_false //defaults to false, add cache busting time stamp to the request?
*/
/* Usage:
new loadXmlHttp({reqObject Properties})
Example:
new loadXmlHttp({url: 'somePage.php', method: 'POST', form: document.forms.myform})
*/
/* Example callback:
function(){
if(this.success(false)){
alert(this.xmlHttp.responseText);
}
}
All native and set properties of the loadXmlHttp instance are availbale to this function as:
this.propertyName
Explanation of this.success():
If the request is successful, and there is an element or an id of an element to populate
set in the original call for this instance of loadXmlHttp and that element exists, this.success()
will return true. If there is no element to populate with the responseText or that element
doesn't exist, and you use:
this.success(false)
It will still return true, as long as the request was successful.
*/
/* How to use the loadXmlHttp.attachForm() function:
This function will allow you to set a form to use loadXmlHttp with only one consolidated call.
Example:
loadXmlHttp.attachForm({form: 'myform', bust: true, id: 'result', method: 'post', callback: function(){
if (this.success()){
/>([^<]*)<\/sp/i.test(this.xmlHttp.responseText);
this.el.innerHTML = RegExp.$1;
}
}
});
Note: When using this method, if a populate element is desired, the el property must be skipped
in favor of the id property, and the form must be represented either by its number in the
document forms collection or by its quoted name.
*/
function loadXmlHttp(req){
if(loadXmlHttp.xmlHttp){
var f = this, r;
for(r in req){
if((req.hasOwnProperty && req.hasOwnProperty(r)) || !req.hasOwnProperty){
f[r] = req[r];
}
}
f.xmlHttp = loadXmlHttp.xmlHttp();
f.el = f.el || (f.id? document.getElementById(f.id) : null);
f.form = typeof f.form === 'object'? f.form : document.forms[f.form];
f.method = f.method? f.method.toUpperCase() : 'GET';
f.url = f.url || location.href;
f.bustCache();
f.url += f.method === 'GET' && f.query? f.qa + f.query : '';
if(f.method === 'GET' && !f.query && f.form){
f.encodeData();
f.url += f.qa + f.data;
}
f.xmlHttp.open(f.method, f.url, true);
if(f.callback !== null){
f.xmlHttp.onreadystatechange = typeof f.callback === 'function'?
function(){f.callback.apply(f);} : function(){f.stateChanged();};
}
if(f.method === 'POST'){
if(f.form){
f.encodeData();
}
f.xmlHttp.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
f.xmlHttp.setRequestHeader('Content-length', f.data? f.data.length : 0);
f.xmlHttp.setRequestHeader('Connection', 'close');
}
f.xmlHttp.send(f.method === 'POST' && f.data? f.data : null);
}
else alert('Your browser does not support AJAX!'); // substitute your desired request object unsupported code here
}
//setup - while parsing:
loadXmlHttp.xmlHttp = null; loadXmlHttp.re = /^http/.test(location.href);
loadXmlHttp.qa = /\?/; loadXmlHttp.chkbl = /^(radio)|(checkbox)$/i;
/*@cc_on @*/ // used here and below, limits try/catch to those IE browsers that both benefit from and support it
/*@if(@_jscript_version >= 5) // prevents errors in old browsers that barf on try/catch & problems in IE if Active X disabled
try {loadXmlHttp.ie = window.ActiveXObject}catch(e){};
@end @*/
if (window.XMLHttpRequest && (!loadXmlHttp.ie || loadXmlHttp.re))
loadXmlHttp.xmlHttp = function(){return new XMLHttpRequest();}; // Firefox, Opera 8.0+, Safari, others, IE 7+ when live - this is the standard method
else if (/(object)|(function)/.test(typeof createRequest))
loadXmlHttp.xmlHttp = createRequest; // ICEBrowser, perhaps others
else {
loadXmlHttp.xmlHttp = null;
// Internet Explorer 5 to 6, includes IE 7+ when local //
/*@if(@_jscript_version >= 5)
try{loadXmlHttp.xmlHttp = function(){return new ActiveXObject("Msxml2.XMLHTTP");};}
catch(e){try{loadXmlHttp.xmlHttp = function(){return new ActiveXObject("Microsoft.XMLHTTP");};}catch(e){}}
@end @*/
}
loadXmlHttp.prototype = {
encodeData: function(){
var els = this.form.elements, chkbl = loadXmlHttp.chkbl; this.data = '';
for(var i = 0; i < els.length; ++i){
if(els[i].name && ((chkbl.test(els[i].type) && els[i].checked) || !chkbl.test(els[i].type))){
this.data += (i? '&' : '') + els[i].name + '=' + encodeURIComponent(els[i].value);
}
}
},
bustCache: function(){
this.qa = loadXmlHttp.qa.test(this.url)? '&' : '?';
if(this.bust){
this.url += this.qa + 'bustacache=' + new Date().getTime();
this.qa = '&';
}
},
success: function(require_el){
return (this.el || require_el === false) && this.xmlHttp.readyState == 4 && (this.xmlHttp.status == 200 || !loadXmlHttp.re);
},
attach: (function(){
return window.addEventListener? function(el, evt, func){el.addEventListener(evt, func, false);}:
window.attachEvent? function(el, evt, func){el.attachEvent('on' + evt, func);} : function(){return;};
})()
};
loadXmlHttp.prototype.stateChanged = function(){
if (this.success()){
if(typeof this.append === 'string'){
this.el.innerHTML += this.append + this.xmlHttp.responseText;
}else{
this.el.innerHTML = this.xmlHttp.responseText;
}
}
};
loadXmlHttp.attachForm = function(req){
var attach = loadXmlHttp.prototype.attach;
attach(window, 'load', function(){
req.form = document.forms[req.form];
attach(req.form, 'submit', function(e){
new loadXmlHttp(req);
if(e && e.preventDefault){
e.preventDefault();
}
return false;
})
});
};
//end setup
Here's a demo taking advantage of some of the new features:
PHP Code:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<style type="text/css">
#result {
width: 28em;
border: 1px solid #ffc0cb;
padding: 0.25em;
min-height: 1em;
}
form {
margin-bottom: 0.75em;
}
#post {
display: none;
}
</style>
<script type="text/javascript" src="http_get_post.js"></script>
<script type="text/javascript">
loadXmlHttp.attachForm({form: 'myform', bust: true, id: 'result', method: 'post', append: '<br>', callback: function(){
if (this.success()){
/>([^<]*)<\/sp/i.test(this.xmlHttp.responseText);
this.el.innerHTML += (this.el.innerHTML !== ''? this.append : '') + RegExp.$1;
}
}
});
</script>
</head>
<body>
<div id="post"><span><?php echo $_POST['list'] . $_POST['name'] . ', ' . $_POST['gender'] . ', country: ' . $_POST['country']; ?></span></div>
<form action="#" name="myform">
<div>
<label>Name: <input type="text" name="name" value=""></label><br>
Gender:<br>
<label>Not Disclosed:<input type="radio" checked name="gender" value="gender not disclosed"></label><br>
<label>Female: <input type="radio" name="gender" value="female"></label><br>
<label>Male: <input type="radio" name="gender" value="male"></label><br>
<label>Add Me to Your List: <input type="checkbox" name="list" value="Added To List: "></label><br>
Country: <select name="country">
<option value="Kenya">Kenya</option>
<option value="UK">UK</option>
<option value="USA">USA</option>
<option value="n/a" selected>None of the Above</option>
</select><br>
<input type="submit" value="Go!">
</div>
</form>
<div id="result"></div>
</body>
</html>
Bookmarks