Ajax getHTTPObject function


/ Published in: JavaScript
Save to your folder(s)

This functions allows you to create a new XMLHTTPRequest, it checks to see if the browser supports each method, if not it returns false.


Copy this code and paste it in your HTML
  1. /*Usage
  2.  * var request = getHTTPObject();
  3.  * if(request){
  4.  * AJAX CODE HERE
  5.  * }
  6.  *
  7.  * If getHTTPObject returns false, the browser isn't Ajax compatible. The if
  8.  * statement checks to see if it exists, then runs the code.
  9.  */
  10. function getHTTPObject() {
  11. var xhr = false;//set to false, so if it fails, do nothing
  12. if(window.XMLHttpRequest) {//detect to see if browser allows this method
  13. var xhr = new XMLHttpRequest();//set var the new request
  14. } else if(window.ActiveXObject) {//detect to see if browser allows this method
  15. try {
  16. var xhr = new ActiveXObject("Msxml2.XMLHTTP");//try this method first
  17. } catch(e) {//if it fails move onto the next
  18. try {
  19. var xhr = new ActiveXObject("Microsoft.XMLHTTP");//try this method next
  20. } catch(e) {//if that also fails return false.
  21. xhr = false;
  22. }
  23. }
  24. }
  25. return xhr;//return the value of xhr
  26. }

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.