Tuesday, July 1, 2014

Step by step how to send a cross-domain Ajax request

        By Carmel Schvartzman


In this tutorial we'll learn how to send a cross-domain Ajax HTTP request using javascript jQuery methods. We'll use the $.ajax() method to render just a sample XML response , fixing the "No 'Access-Control-Allow-Origin' header is present on the requested resource" error.

Let's say you have a web page which sends HTTP GET or HTTP POST requests to a web service (WCF endpoint or OData service) to load the data :





Everything works fine , provided that BOTH the client and the web services are in the SAME DOMAIN. The problem will arouse while the client and the server are hosted in DIFFERENT DOMAINS :





We got an  "No 'Access-Control-Allow-Origin' header is present on the requested resource" error, and there are "provisional" headers displayed.
Why? Because in the case of AJAX cross-domain requests, the browser sends some kind of "PRE-REQUEST" to  the web server, of the type of HTTP OPTIONS verb, informing that a CROSS-DOMAIN violation is being produced. Is then up to the web server to send or not a response to the web client.
That's because cross-domain HTTP requests started from scripts are subject to security restrictions. The 'CORS' (Cross Origin Resource Sharing) policy,  prevents access to methods and properties across DOMAINS, that means,  pages on different  web sites will not successfully retrieve data from some other domain, subdomain, or even internet protocol. For example, some resource loaded from  the domain http://AAAdomain.com)   makes a HTTP request for a resource on OTHER domain such as  http://BBBdomain.com . A web application can only make HTTP requests via AJAX to the domain to which it belongs, and not to other domains.
You can access to in-deep information about CORS policy in this web site.
To solve the  problem, we'll simply set the "Access-Control-Allow-Origin" header on our web server, setting it to "*" , in order to accept cross-domain AJAX HTTP requests from different domains.

Our Ajax request will be as follows:

 $.ajax(              {  

    crossDomain: true,

                url: url,
                type: "GET",
                contentType: "text/plain", 
                dataType: "xml",
                data: "",
                success: function (data)
                {                   
                    $(data).find('entry').each(function (index) {                         
                     
                        var id = $(this).find('BlogID').text();  
                        var title = $(this).find('Title').text();  
                        var text = $(this).find('Text').text();
                        var img = $(this).find('MainPicture').text();                        
                       
                    });                   
                                   },
                error: function (res) {
                    alert(res.status);
                }            });





And inside the <system.webServer> element at the web.config of the web server we'll set the headers to "*" :







<!--<httpProtocol>  --><!--THIS IS FOR CORS POLICY--><!--
      <customHeaders>

          <add name="Access-Control-Allow-Origin" value="*" />
          <add name="Access-Control-Allow-Headers" value="Content-Type" />
          <add name="Access-Control-Allow-Methods" value="POST, GET, OPTIONS" />
      </customHeaders>
  </httpProtocol>-->  </system.webServer>  



That's all we must get done, to enable cross-domain AJAX requests.

In this tutorial we've learned how to send a cross-domain Ajax request using javascript jQuery methods,  fixing the "No 'Access-Control-Allow-Origin' header is present on the requested resource" error.

That's all!! 
Happy programming.....

כתב: כרמל שוורצמן