What more is needed for Ajax than this feature

I have a small JS function that does Ajax for me, and the other adds data to the POST request. Since Ajax is such a big topic in which there are so many libraries that I miss in my function, is it insecure or something else bothering?

function loadPage(pagePath, displayElement) { var xmlHttp; try { // Firefox, Opera 8.0+, Safari xmlHttp=new XMLHttpRequest(); } catch (e) { // Internet Explorer try { xmlHttp=new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) { try { xmlHttp=new ActiveXObject("Microsoft.XMLHTTP"); } catch (e) { alert("Your browser does not support AJAX!"); return false; } } } xmlHttp.onreadystatechange=function() { if(xmlHttp.readyState==4) { document.getElementById(displayElement).innerHTML = xmlHttp.responseText; } } xmlHttp.open("GET", pagePath, true); xmlHttp.send(null); } 
+4
javascript ajax
source share
6 answers

I highly recommend that you don't roll your own Ajax code. Instead, use a framework like Prototype, Dojo, or whatever. They made sure to handle all ReadyStates that you are not processing (2 means that they were sent, 3 means that they are running, etc.), and they should avoid the answer that you get so that you don't insert potentially unsafe javascript or something on your page.

Another thing a more robust structure offers you is the ability to do more than just use innerHTML to replace elements in the DOM. Your function here can only be used to replace one element with a response from an ajax call. There is so much more you can do with Ajax.

+12
source share

I would delete this line.

 alert("Your browser does not support AJAX!") 

Shouting at a user in a language that he probably does not understand is worse than failure. :-)

+6
source share

I have never been a fan of nested try / catch blocks, so I would do something like:

 var xmlHttp; if (window.XMLHttpRequest) { // Firefox, Opera 8.0+, Safari xmlHttp=new XMLHttpRequest(); } else if (window.ActiveXObject) { try { xmlHttp=new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) { xmlHttp=new ActiveXObject("Microsoft.XMLHTTP"); } } if (xmlHttp) { // No errors, do whatever you need. } 

I think it will work. But, as mentioned earlier, why reinvent the wheel, use the library. Better yet, find out how they do it.

+3
source share

Same thing in prototype:

 function loadPage(pagePath, displayElement) { new Ajax.Updater(displayElement, pagePath); } 

Ajax.Updater in prototype API

+2
source share

jQuery is probably one of the lightest popular libraries.

+1
source share

If you really want to know what is missing, read the jQuery or Prototype source code for your ajax routines. If there are error numbers in the comments, review them as well.

0
source share

All Articles