Antoine Cloutier
Antoine Cloutier

Reputation: 1330

Calling a web service on a remote server with jQuery

I have been stuck on this issue for hours now, unable to find a valid answer, perhaps because of my lack of knowledge/experience with such things.

I am aware that I cannot load a web service on a remote server with XMLHttpRequest due to Same-Origin restriction, but apparently this can be done with jsonp data type and providing a callback function but I really can't figure out how to make it work.

The remote server would be mine, so I don't really care about the possiblity that the remote server can send back any malicious javascript code.

I would appreciate if anyone could help me to get some working code with the web service at http://www.antoinecloutier.com/WebService1.asmx/HelloWorld

I have created a test page on my server and the web services works fine --> http://antoinecloutier.com/test.html

Now, I need to be able to access that web service from a different server.

Thank you!

Upvotes: 3

Views: 6271

Answers (1)

Jatin patil
Jatin patil

Reputation: 4288

You can make Cross Domain AJAX Calls using jquery by enabling CORS

For eg:

 jQuery.support.cors = true;
    $.ajax({
        url: 'http://crossdomainurl',
        type: 'GET',
        dataType: 'json', 
        contentType: "application/json; charset=utf-8",           
        success: function (data) {                
            WriteResponse(data);
        },
        error: function (x, y, z) {
            alert(x + '\n' + y + '\n' + z);
        }
  });

To Make Sure Cross Domain Work Properly you will have to add a Access-Control-Allow-Origin: * response header to the web service response.

In a .NET WCF service, you can add this to the global.asax of your service as follows,

protected void Application_BeginRequest(object sender, EventArgs e)
{
    HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin","*");
}

In PHP you can modify the response as follows,

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

Note:

Sending the Access-Control-Allow-Origin header allows basic cross-origin access, but calling ASP.NET services like ASMX ScriptServices, ASPX page methods, and WCF services with AspNetCompatibilityRequirements enabled requires your site to respond with one additional CORS header: Access-Control-Allow-Headers

You can configure the same in web.config as follows,

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

Upvotes: 4

Related Questions