I'm looking for an AJAX function to dynamically request an HTML page. I already found the following:
function ajaxinclude(url)
{
var page_request = false
if (window.XMLHttpRequest) // if Mozilla, Safari etc
page_request = new XMLHttpRequest()
else if (window.ActiveXObject) // if IE
{
try {
page_request = new ActiveXObject("Msxml2.XMLHTTP")
}
catch (e){
try{
page_request = new ActiveXObject("Microsoft.XMLHTTP")
}
catch (e){}
}
}
else
return false
page_request.open('GET', url, false) //get page synchronously
page_request.send(null)
return page_request.responseText;
}
It works fine in Firefox and Chrome, but it fails in IE on the following line:
page_request.open('GET', url, false)
Is there a better available function that is guaranteed to be completely cross browser compatible?
Edit: Thanks for all the great suggestions... in the end, I decided not to reinvent the wheel here. And one of the things I forgot to mention was that I also need it to update at an interval... though I had already figure that out so I didn't think it made a difference. But then I found the great Ajax.PeriodicUpdater() Method in prototype and vastly changed my mind. I just went from a 50 LOC solution to about 4 lines :)
I would have to agree, don't go reinventing the wheel, or in this case, AJAX.
JQuery and Prototype do an excellent job of letting you NOT have to deal with cross-browser support, and greatly simplifying Javascript type programming. I fell into JQuery first so I'm biased towards it, and from what I've seen the library is a little smaller (read: faster in the browser), but Prototype I believe has been around longer and has TONS of plugins and examples out there. Ruby on Rails also by default uses Prototype. Funny enough, the code in both looks very similar and takes little rewriting to change libraries.
JQuery Tutorials <-- Just head on down to the AJAX section
Or you can try this if you don't need an entire framework: http://www.hunlock.com/blogs/The_Ultimate_Ajax_Object
I would suggest using any of a number of different javascript frameworks for this functionality instead of reinventing it. There's jQuery, Prototype/Scriptaculous, MooTools, Dojo, and many others. All of these offer cross-browser support for what you are doing.
I recommend jQuery, but there is also a very lightweight solution: XHConn
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With