The example returns the data to the browser in a simple DSV (delimiter-separated values) format.
Tutorial Details:
Preparing Form Data to POST
Other resources online covering the XMLHttpRequest object demonstrate how to use it with simple GET requests. The object is also capable of doing POSTs, which makes it a much more useful tool for creating web applications.
To use the POST method, pass data to the XMLHttpRequest object in query-string format (for example, ArtistName=Kolida&SongName=Wishes), which the object then sends to the server just like a normal form POST. You can use JavaScript to pull data a piece at a time out of web-form elements, and then format the data into a query string. If I wanted to do this for my playlist search function, I could use something like this:
var searchForm = document.forms['searchForm'];
var artistName = searchForm.ArtistName.value;
var songName = searchForm.SongName.value;
var queryString = '?ArtistName=' + escape(artistName) + '&SongName=' +
escape(songName);
Note: Be sure to escape (URL encode) the values.
Of course, keeping in mind that one of Larry Wall's three great virtues of a programmer is laziness (and in that respect I'm really virtuous), I wrote a general function to automate this process, to put all the data from a form into a query string. This function allows me to POST form data with the XMLHttpRequest object without having to do a lot of extra work every time. That makes it significantly easier to integrate the use of the object with my existing application code.
Creating the Object
To create the object in JavaScript for IE, use new ActiveXObject("Microsoft.XMLHTTP"). In Mozilla/Firefox and Safari, use new XMLHttpRequest(). The first half of a simple function to create and use the object looks like this:
function xmlhttpPost(strURL, strSubmit, strResultFunc) {
var xmlHttpReq = false;
// Mozilla/Safari
if (window.XMLHttpRequest) {
xmlHttpReq = new XMLHttpRequest();
xmlHttpReq.overrideMimeType('text/xml');
}
// IE
else if (window.ActiveXObject) {
xmlHttpReq = new ActiveXObject("Microsoft.XMLHTTP");
}
To make this a reusable, generic function, I pass in three parameters: the URL for the processing page on the server, the query-string formatted data to submit, and the name of the JavaScript function that will process the response from the server (to invoke later through eval).
Note the addition of the overrideMimeType method call in the Mozilla/Safari code. Without this, some people have reported that some versions of Mozilla lock up when the server returns anything other than XML. (I cannot confirm this issue, as I have not experienced this problem myself.)
Also, if you want to support older browsers, you can then test the xmlHttpReq variable and fall back to other methods of submitting data if the object is not present.
Read
Tutorial at: Click here to view the tutorial
Rate Tutorial: A Simpler Ajax Path
View Tutorial: A Simpler Ajax Path
Related
Tutorials:
|