|
Back to the Konsensys Back to Tips |
Simpler JavaScript Code to Implement AJAX
by
George Van Treeck
|
You will find other websites describing some overly complicated cross-browser AJAX code. Specifically, they recommend using several versions of Microsoft's MSXML libraries to support each version of Microsoft's browsers. This is an urban myth. The fact is that you can use the same XMLHttpRequest object that you use for all other browsers. Below is a short snippet of JavaScript code that works for all AJAX-enabled browsers and is used in applications generated the Konsensys DreamBeans tool:
try {
http = new XMLHttpRequest();
} catch (e) {
alert('AJAX Error ' + e.target.status +
' occurred. This browser does not ' +
'support XMLHttpRequest.');
return false;
}
http.open(form.method, url, false);
http.onError = function() {
alert('AJAX Error ' + e.target.status +
' occurred while receiving the document.');
}
try {
http.setRequestHeader('Content-Type',
'application/x-www-form-urlencoded');
http.send(queryString);
} catch (e) {
alert('AJAX Error ' + e.target.status +
' occurred while sending the query string.');
return false;
}
if (http.readyState == 4 && http.status == 200) {
document.charset='UTF-8';
document.defaultCharset='UTF-8';
// Your code starts here
response = http.responseText; // Or get XML if using DOM
div_element = document.getElementById('some_id');
// insert into div_element using either DOM or innerHTML
// Done with your code
return false;
}
alert('AJAX Error: contents not replaced.');
return false;
}
To see complete example in use. You can go the website, BestPicker website and view the source HTML. |
Copyright (C) 2010 George Van Treeck. All rights reserved.