Wednesday 19 September 2012

Cross-domain data with AJAX using JSON

I read some different blogs and sites about using JSON or JSONP in relation with AJAX requests in cross-domain environments.
I just want it to keep it as simple as possible.
Situation:
I have a local webservice, behind a firewall, which is only available from another website somewhere on the internet (ip-filtering). On that site I call the (local) webservice) using
$.ajax({
  type: "POST",
  url: 'http://<my url:portnumber>/myCustomService.asmx/SendMyRequest',
  data: "{name: '" + _name
  + "' , category: '" + _category
  + "' , address: '" + _address
  + "' , company: '" + _company + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
  // etc...

So, I figured out to use "access-control-allow-origin" with the value "*" as a custom header in IIS7.5
Problem:
However, adding the Acces-control-allow-origin=* doesn't work. After some struggling and some more research, in found the solution
Solution:
Besides this access-control-allow-origin, you need to add an extra entry, the "access-control-allow-headers" with value "content-type". So, just place inside your web.config the following data:

<configuration>
  <system.webServer>
    <httpProtocol>
      <customHeaders>
        <add name="access-control-allow-origin" value="*" />
        <add name="access-control-allow-headers" value="content-type" />
      </customHeaders>
    </httpProtocol>
  </system.webServer>
</configuration>

No comments: