Skip to main content

AJAX, Cross Domain, XMLHttpRequest, XDomainRequest Over IE8 FF8 and Chrome

Ok.I have been faced for this cross domain request using ajax last week and i got real pain when i tried to use it.
I tried with jquery ajax and read lots of articles from the Internet. Reading made me to do this post.
First i tell you what was my scene. I had to do a validation regarding some value. I request this via Ajax.




Problems

My Origin (requesting ajax call from)

https://www.domain.com/

My Validation result and requested output

https://sub.domain.com

Here is the deal. Normally you cant do below

Access remote content which different from current protocol://domain.com.
example:
Requesting https://sub.domain.com content from https://www.domain.com/
Requesting http://www.domain.com content from https://www.domain.com/
Requesting http://www.domain.com:80 content from https://www.domain.com:8080

still you have same domain and want to make a call to your sub domain....No you cant.
Even in my sample function. I cant access https from http or https from http ONLY FOR IE8.Other browsers are working. I think you understand me. (My next attempt would be resolve this IE8 Problem).
In my function i manage to fulfill my requirement and hopefully this might help you to enhance, read or use your requirement.
Anyway you can dive in the Internet to get enough details(I spend lots of time...:-P)


also you have to remember the content page your going to request should contain following header type included.



Access-Control-Allow-Origin: *

With php you can add as below

<?php header('Access-Control-Allow-Origin: *'); ?>

Here is my Code.

<html>
<head>
<title>AJAX</title>
<script type="text/javascript" src="jquery-1.7.1.js"></script>
<script type="text/javascript">

var XHR ;

function createXMLHttp() 
{
 if (typeof XMLHttpRequest != "undefined")
 {
  if(window.XDomainRequest)
  {
   return new XDomainRequest();
  }
  else
  {
   return new XMLHttpRequest();
  }
 }
 else if (window.ActiveXObject) 
 {
  var aVersions = ["MSXML2.XMLHttp.5.0","MSXML2.XMLHttp.4.0","MSXML2.XMLHttp.3.0","MSXML2.XMLHttp","Microsoft.XMLHttp"];
  
  for (var i = 0; i < aVersions.length; i++) 
  {
   try
   {
    var oXmlHttp = new ActiveXObject(aVersions[i]);
    return oXmlHttp;
   }
   catch(oError)
   {
    throw new Error("XMLHttp object could be created.");
   }
  }
 }
 throw new Error("XMLHttp object could be created.");
}

function makeAjaxRequest(url)
{
 XHR = new createXMLHttp();
 
 if(XHR)
 {
  XHR.open('GET',url, true);
  //XHR.onreadystatechange = handler; 
  XHR.onload = function() 
       {
        if (XHR.readyState == 4)
        {
         //Chrome 17 and FF 8.0
         if (XHR.status == 200)
         {
          response =eval("("+XHR.responseText+")");
          $("#res-text").html("Name : " + response.name + "<br/>Company Overview : " + response.company_overview);          
         }
         else
         {
          alert("Invocation Errors Occured " + XHR.readyState + " and the status is " + XHR.status);
         }
        }
        else
        {
         //IE8
         response =eval("("+XHR.responseText+")");
         $("#res-text").html("Name : " + response.name + "<br/>Company Overview : " + response.company_overview);
        }
       
        
       }; 
  XHR.send(null); 
 }
 else
 {
  alert("Cannot Make Ajax Request");
 }

}

function handler(evtXHR)
{
 if (XHR.readyState == 4)
 {
  if (XHR.status == 200)
  {
   response =eval("("+XHR.responseText+")");
   //$("#res-text").html("Name : " + response.name + "\nCompany Overview : " + response.company_overview);
   alert(response.name);
  }
  else
  {
   alert("Invocation Errors Occured " + XHR.readyState + " and the status is " + XHR.status);
  }
 }
 else
 {
  //"currently the application is at" + XHR.readyState);
 }
}

makeAjaxRequest('https://graph.facebook.com/19292868552');

</script>


</head>

<body style="background:#001122; color:#FFFFFF; font-size:13px;font-family:'Verdana'">

<div id="res-text" ></div>
</body>

</html><html>
<head>
<title>AJAX</title>
<script type="text/javascript" src="jquery-1.7.1.js"></script>
<script type="text/javascript">

var XHR ;

function createXMLHttp() 
{
 if (typeof XMLHttpRequest != "undefined")
 {
  if(window.XDomainRequest)
  {
   return new XDomainRequest();
  }
  else
  {
   return new XMLHttpRequest();
  }
 }
 else if (window.ActiveXObject) 
 {
  var aVersions = ["MSXML2.XMLHttp.5.0","MSXML2.XMLHttp.4.0","MSXML2.XMLHttp.3.0","MSXML2.XMLHttp","Microsoft.XMLHttp"];
  
  for (var i = 0; i < aVersions.length; i++) 
  {
   try
   {
    var oXmlHttp = new ActiveXObject(aVersions[i]);
    return oXmlHttp;
   }
   catch(oError)
   {
    throw new Error("XMLHttp object could be created.");
   }
  }
 }
 throw new Error("XMLHttp object could be created.");
}

function makeAjaxRequest(url)
{
 XHR = new createXMLHttp();
 
 if(XHR)
 {
  XHR.open('GET',url, true);
  //XHR.onreadystatechange = handler; 
  XHR.onload = function() 
       {
        if (XHR.readyState == 4)
        {
         //Chrome 17 and FF 8.0
         if (XHR.status == 200)
         {
          response =eval("("+XHR.responseText+")");
          $("#res-text").html("Name : " + response.name + "<br/>Company Overview : " + response.company_overview);          
         }
         else
         {
          alert("Invocation Errors Occured " + XHR.readyState + " and the status is " + XHR.status);
         }
        }
        else
        {
         //IE8
         response =eval("("+XHR.responseText+")");
         $("#res-text").html("Name : " + response.name + "<br/>Company Overview : " + response.company_overview);
        }
       
        
       }; 
  XHR.send(null); 
 }
 else
 {
  alert("Cannot Make Ajax Request");
 }

}

function handler(evtXHR)
{
 if (XHR.readyState == 4)
 {
  if (XHR.status == 200)
  {
   response =eval("("+XHR.responseText+")");
   //$("#res-text").html("Name : " + response.name + "\nCompany Overview : " + response.company_overview);
   alert(response.name);
  }
  else
  {
   alert("Invocation Errors Occured " + XHR.readyState + " and the status is " + XHR.status);
  }
 }
 else
 {
  //"currently the application is at" + XHR.readyState);
 }
}

makeAjaxRequest('https://graph.facebook.com/19292868552');

</script>


</head>

<body style="background:#001122; color:#FFFFFF; font-size:13px;font-family:'Verdana'">

<div id="res-text" ></div>
</body>

</html><html>
<head>
<title>AJAX</title>
<script type="text/javascript" src="jquery-1.7.1.js"></script>
<script type="text/javascript">

var XHR ;

function createXMLHttp() 
{
 if (typeof XMLHttpRequest != "undefined")
 {
  if(window.XDomainRequest)
  {
   return new XDomainRequest();
  }
  else
  {
   return new XMLHttpRequest();
  }
 }
 else if (window.ActiveXObject) 
 {
  var aVersions = ["MSXML2.XMLHttp.5.0","MSXML2.XMLHttp.4.0","MSXML2.XMLHttp.3.0","MSXML2.XMLHttp","Microsoft.XMLHttp"];
  
  for (var i = 0; i < aVersions.length; i++) 
  {
   try
   {
    var oXmlHttp = new ActiveXObject(aVersions[i]);
    return oXmlHttp;
   }
   catch(oError)
   {
    throw new Error("XMLHttp object could be created.");
   }
  }
 }
 throw new Error("XMLHttp object could be created.");
}

function makeAjaxRequest(url)
{
 XHR = new createXMLHttp();
 
 if(XHR)
 {
  XHR.open('GET',url, true);
  //XHR.onreadystatechange = handler; 
  XHR.onload = function() 
       {
        if (XHR.readyState == 4)
        {
         //Chrome 17 and FF 8.0
         if (XHR.status == 200)
         {
          response =eval("("+XHR.responseText+")");
          $("#res-text").html("Name : " + response.name + "<br/>Company Overview : " + response.company_overview);          
         }
         else
         {
          alert("Invocation Errors Occured " + XHR.readyState + " and the status is " + XHR.status);
         }
        }
        else
        {
         //IE8
         response =eval("("+XHR.responseText+")");
         $("#res-text").html("Name : " + response.name + "<br/>Company Overview : " + response.company_overview);
        }
       
        
       }; 
  XHR.send(null); 
 }
 else
 {
  alert("Cannot Make Ajax Request");
 }

}

function handler(evtXHR)
{
 if (XHR.readyState == 4)
 {
  if (XHR.status == 200)
  {
   response =eval("("+XHR.responseText+")");
   //$("#res-text").html("Name : " + response.name + "\nCompany Overview : " + response.company_overview);
   alert(response.name);
  }
  else
  {
   alert("Invocation Errors Occured " + XHR.readyState + " and the status is " + XHR.status);
  }
 }
 else
 {
  //"currently the application is at" + XHR.readyState);
 }
}

makeAjaxRequest('https://graph.facebook.com/19292868552');

</script>


</head>

<body style="background:#001122; color:#FFFFFF; font-size:13px;font-family:'Verdana'">

<div id="res-text" ></div>
</body>

</html>
 

Read More: http://hacks.mozilla.org/2009/07/cross-site-xmlhttprequest-with-cors/

Leave a comment. Cheers.

Comments

  1. No point in checking XHR.readyState when you use onload. Onload is only invoked when XHR.readyState == 4 and XHR.status == 200. Basically it's a special case of onreadystatechange

    ReplyDelete

Post a Comment

Popular posts from this blog

Application Configuration FIle Visual Studio 2005

Through the application configaration file You can easily save values to later usage. you can create a application configuration file from project > Add New Item (Ctrl + Shift + A) example You want to add get string from config file Create a Config file using above step. after that insert following code to the config file. its a XML file. appsettings add key="DatabasePath" value="c:\\projects\data\spider.mdb" add key="SupportEmail" value="webmaster-1@dotnetspider.com" appsettings configuration in the coding add following Dim app As New System.Configuration.AppSettingsReader Dim s As String s = app.GetValue("DatabasePath", Type.GetType("System.String")) MessageBox.Show(s) its very easy when you are handling databases. you can store database connection string in that config for later reusabilty. Please post your comments

Expire Session When the Browser Close [Codeigniter]

I wanted user to log again to the site whenever they close the browser. i searched everywhere and i found the easiest way. application/config/config.php sess_expire_on_close = TRUE Easy Session Preferences You'll find the following Session related preferences in your file: Preference Default Options Description sess_cookie_name ci_session None The name you want the session cookie saved as. sess_expiration 7200 None The number of seconds you would like the session to last. The default value is 2 hours (7200 seconds). If you would like a non-expiring session set the value to zero: 0 sess_expire_on_close FALSE TRUE/FALSE (boolean) Whether to cause the session to expire automatically when the browser window is closed. sess_encrypt_cookie FALSE TRUE/FALSE (boolean) Whether to encrypt the session data. sess_use_database FALSE TRUE/FALSE (boolean) Whether to save the session data to a database. You must...