Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cross browser AJAX function to dynamically load HTML

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 :)

like image 306
Adam Haile Avatar asked Jan 11 '09 01:01

Adam Haile


4 Answers

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

like image 190
Adam Avatar answered Nov 10 '22 17:11

Adam


Or you can try this if you don't need an entire framework: http://www.hunlock.com/blogs/The_Ultimate_Ajax_Object

like image 8
Luca Matteis Avatar answered Nov 10 '22 17:11

Luca Matteis


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.

like image 6
tvanfosson Avatar answered Nov 10 '22 17:11

tvanfosson


I recommend jQuery, but there is also a very lightweight solution: XHConn

like image 3
Vadim Ferderer Avatar answered Nov 10 '22 19:11

Vadim Ferderer