Passing form data with AJAX
Some time ago I’ve tried to pass form data with AJAX without using any framework. my jQuery or Mootools. They are great scripts but in most of my cases they over-do the job, so therefor I’ve tried to do it myself, at first I managed to send the post data BUT the format was wrong. anyway to make a long story short here is how I did it.First of all we need to create a .js file which we will include to the html enter the following code in the .js file
function update_form(myForm) {
http_request = false;if (window.XMLHttpRequest) {
http_request = new XMLHttpRequest();
if (http_request.overrideMimeType) {
http_request.overrideMimeType(’text/xml’);
}
} else if (window.ActiveXObject) {
try {
http_request = new ActiveXObject(”Msxm12.XMLHTTP”);
} catch (e) {
try {
http_request = new ActiveXObject(”Microsoft.XMLHTTP”);
}
catch (e) {}
}
}
if (!http_request) {
alert(’Error create XMLHTTP instance’);
return false;
}
theForm = document.getElementById(’theform’);
<!--- this is the tricky part, we need to get the post data and reformat it to an valid array -->
theStr = ”;
for (i=0; i < theForm.elements.length; i++) {
ele = theForm.elements[i];
theStr += ele.name + ‘ = ‘ + ele.value + “&”;
}
url = “foo.php”;
theStr = encodeURI(theStr);
url = encodeURI(url);
http_request.onreadystatechange = update_form2;
http_request.open(’POST’, url, true);
http_request.setRequestHeader(”Content-type”, “application/x-www-form-urlencoded”);
http_request.setRequestHeader(”Content-length”,theStr.length);
http_request.setRequestHeader(”Connection”, “close”);
http_request.send(theStr);
}
function update_form2() {
if (http_request.readyState == 4) {
if (http_request.status == 200) {
document.getElementById(’status’).innerHTML = http_request.responseText;
} else {
alert(’Have problems loading new page’);
}
}
}
Okay once this is done, the easy part starts.
Create a form and give the form the following ID id=”theform” inside the header of our file we include the previous created .js file
once this is done and working we need a file that is capable of processing the data. This depends on yor needs but to see if it is working create a file foo.php and enter the following piece of code.
<?php
echo print_r($_POST, true);
?>
This file will dispay an array map of the keys and values that where send from your form.
Enjoy it, and feel free to modify it, if you have any question regarding this little tut feel free to leave a message.
Tags: AJAX, Javascript, programming























