Edgar
Edgar

Reputation: 282

Chrome shows Access Control Allow Origin error

I'm using jquery to post data to a server, the server received the data, but the chrome still shows the error :

XMLHttpRequest cannot load `myServer:63373/api/sendData`. Origin `myServer:63385` is not allowed by Access-Control-Allow-Origin. 

Here is my js code:

 $.ajax({
            type: 'POST',
            url: 'myServer:63373/api/SendData',
            crossdomain: true,
            async: true,
            data: myData,
            dataType: 'json',
            success: function(){ alert('success'); }
        });

The strange thing is that the 'success' shows up after the request, and the server did receive the data, but then the error message shows up in the console. Is there any way to avoid this message?

Upvotes: 1

Views: 13950

Answers (3)

Edgar
Edgar

Reputation: 282

Thanks for all you answers above but I think I've found the way, before I solve this I was trying to use two ways, Setting Access-Control-Allow-Origin in ASP.Net MVC - simplest possible method with the 87 votes and 32 votes, I found the answers at two different places, and both applied them, but it didn't work. Early this week, I tried to delete the code in the web.config and just left the code in C#, it works! Can't believe these two solutions have confliction.

Anyway, hope this could help others.

Upvotes: 4

developerCK
developerCK

Reputation: 4506

if situation are

  • your script is hosted on another server

  • or subdomain

  • or try to hit url with another port

this is cross-domian request. jquery can not fulfill cross-domain request.

if this is your issue , then you should use jsonp for this "jsonp " allows cross domain request.

try to do this with using jsonp.

for jsonp every call has a callback means there will be a value in url and you have to send respnse with this call back in php

means try this:-

$.ajax({
        type: 'POST',
        url: 'myServer:63373/api/SendData',
        crossdomain: true,
        async: true,
        data: myData,
        dataType: 'jsonp',
        success: function(){ alert('success'); }
    });

and in php

wrap your response in  $_GET['_callback']."(".$response.")"; and echo it

you will get response in json .

Upvotes: 0

David-SkyMesh
David-SkyMesh

Reputation: 5171

"not allowed by Access-Control-Allow-Origin" is the reason. Put simply, you can't normally do an XHR call to a different domain/port/protocol from those of the webpage your javascript was included into.

Modern browsers allow you work around this with permission from the server administrator.

You make your Ajax request with the XHR2 API (http://www.html5rocks.com/en/tutorials/cors/)

The on the server side, you need to emit the following headers to allow access from the domain that served the page that included your javascript:

Access-Control-Allow-Origin: http://your-page-domain.com
Access-Control-Allow-Credentials: true

Upvotes: 0

Related Questions