Chrome shows Access Control Allow Origin error - javascript

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?

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.

"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

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 .

Related

how to pass a javascript code in jsonp format and execute

Can we use jsonp to overcome same domain policy of JS.
I need to run script from a domain x to run on domain y. So is it possible to send a script and execute ??
Yes, that is the entire point of JSONP.
There is no restriction on where you can load a script from (other then the usual http/https conflicts).
You can import a JS/CSS file from any other domain.
If you need to GET data from some other domain, you will need to get it through JSONP.
Please note that cross domain requests work only for HTTP/S GET and the only format of data accepted is JSONP.
e.g.
my code using jquery
$.ajax({
url: 'https://www.otherDomain.com',
type: "GET",
crossDomain: true,
data: parameters,
dataType: "jsonp",
jsonpCallback: "localJsonpCallback"
});
function localJsonpCallback(json) {
/* Do stuff */
}
The server side response needs to be in JSONP.

consuming PHP service returning valid json with $.ajax

I've been stuck on consuming a web service created in PHP, not sure what I'm doing wrong.. Ive created a fiddle example here : http://jsfiddle.net/e97AV/
I've tried various combinations of things but keep on getting 404 not found feedback, when I specify jsonp i get no error message, but in the web console i can see a 404 error.. in the browser when I visit the url it is returning valid json
My question is how would I know when to use jsonp or json? Also these service have been provided to me from an external source other than agreeing on json being returned how would I know if the problem is on my side or theirs?
heres the ajax code
baseUrl = "http://exclusivegetaways.co.za/api.php";
$.ajax({
type: "GET",
url: baseUrl,
data: {something : "something"},
//contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (result) {
alert("works");
alert(result);
},
error: function (a,b,cc) {
alert(a+b+cc);
}
});
I've since been able to pull json data from the ajax error object?? like so:
baseUrl = "http://exclusivegetaways.co.za/api.php?something=something";
$.ajax({
type: "GET",
url: baseUrl,
dataType: "json",
success: function (res) {
alert("worked");
//alert(res);
},
error: function(jqxhr) {
try {
f = JSON.parse(jqxhr.responseText);
...valid json returned here
} catch(err) {alert(err);}
}
});
This is because of a security restriction that prevents Ajax from querying remote locations.
As a workaround to enable access to a remote location via Ajax, you could build a custom URL in your webApp (in PHP for instance) which queries the distant API and returns JSON.
Then, in your JavaScript, you call this URL (from your application) via Ajax.
First: Always look at your JavaScript error console.
XMLHttpRequest cannot load http://exclusivegetaways.co.za/api.php?location=provinces.
No 'Access-Control-Allow-Origin' header is present on the requested resource.
Origin 'http://fiddle.jshell.net' is therefore not allowed access.
See also Ways to circumvent the same-origin policy
I've tried various combinations of things but keep on getting 404 not found feedback, when I specify jsonp i get no error message, but in the web console i can see a 404 error. in the browser when I visit the url it is returning valid json
This suggests that:
They don't support JSONP
They look at the HTTP headers and 404 your request to block access from Ajax (this isn't a good way to do that, the error code is misleading)
My question is how would I know when to use jsonp or json?
Usually by reading the documentation for the server you are trying to use
Also these service have been provided to me from an external source other than agreeing on json being returned how would I know if the problem is on my side or theirs?
Usually by working with whatever support is provided by the API provider (i.e. start with their documentation, then fall back to whatever means they provide for communicating with a human).
Due to Same Origin Policy your ajax request is allowed only if:
domain name, application layer protocol, and (in most browsers) port
number of the HTML document running the script are the same
In your case the application layer protocol is different, that's why your script fails.
Possible solutions are:
JSONP, which has to be provided by the server
CORS, which is a more 'elegant' and clean solution, but is not yet fully supported by IE (IE7 doesn't support it, IE8 has some limitations)
Answer taken from this link

crossdomain.xml configuration

I have to call to a web service from javascript using ajax:
$.ajax({
type: "GET",
url: "http://[REMOTE-SERVER-IP]:8080/api/service",
contentType: "application/jsonp",
crossDomain: true,
success: successFunc,
error: errorFunc
});
I read that to grant access to the method, a "crossdomain.xml" must be created in the server http://[REMOTE-SERVER-IP]:8080/crossdomain.xml:
<cross-domain-policy>
<allow-access-from domain="[SERVICE-CALLER-IP]"/>
</cross-domain-policy>
But after doing that, when I try to call to the method, I'm getting this error from the javascript debugger:
XMLHttpRequest cannot load http://[REMOTE-SERVER-IP]:8080/[URL]. Origin http://localhost:8080 is not allowed by Access-Control-Allow-Origin
What am I doing bad?
Thank you very much!!!
You can prefer two options here and both assumes that you can access the server.
The first option is to add callback=? parameter to request url, and modify the server response. Server should add the callback function to the response in the following format
callback_function_coming_from_url([your_server_response])
The second option is to add Access-Control-Allow-Origin: * header to your server response. Or you can specify the address like Access-Control-Allow-Origin: [your_client_address]
I prefer to option 2 since it is the convenient way to accomplish your task, and also, you can control your server response, much more secure than the option 1.
You can get additional info from CORS

jQuery 1.5 only sends GET requests in ajax method

I am trying to make a PUT request to a RESTful web service, however, it appears that jQuery 1.5 does respond to any changes in the 'type' setting. The request is sent as a GET no matter the value in 'type'. In jQuery 1.4 this isn't a problem.
Here's my code:
$.ajax({
type: "PUT",
url: "https://api.somesite.com/v1.0/people/" + individualID + "/",
dataType: "jsonp",
data: $("#editProfile").serializeArray(),
cache: "false",
success: function(data,textStatus,jqXHR) {
$.modal.close();
},
error: function(jqXHR,textStatus,errorThrown) {
alert("Error!");
}
});
As far as I'm aware, you can't make a JSONP request via PUT. Since JSONP works by injecting a <script> element pointing to the remote domain, that request will always be a GET request.
If you absolutely must make a PUT request to a remote domain, you'll need to either use a server-side proxy on your local domain or look into CORS if you don't need IE support.
From the jQuery.ajax() docs:
The type of request to make ("POST" or
"GET"), default is "GET". Note: Other
HTTP request methods, such as PUT and
DELETE, can also be used here, but
they are not supported by all
browsers.
Perhaps with some additional browser info we can figure out what is causing the problem, but for now it seems jQuery does not want to guarantee functionality except on GET and POST. This is surprising for me to find out =)
How do I PUT data to Rails using JQuery maybe?
edit: oups, you didnt say the webservice was in Rails. But it might support something like that too. Did you try just sending a POST request?
I was struggling with something similar. I have been able to send a PUT successfully pre 1.5 but stopped working with 1.5. I know there was a big change to how the ajax stuff in handled in 1.5 so I'll look into that next.
When it did work it worked fine for me in safari, firefox & chrome. When it works you'll first get an OPTIONS being sent and as pointed out before your server side will have to response satisfactorily to the OPTIONS request a la CORS. Here is a piece ot test code that does work for me pre 1.5 so it is possible. As an aside I was not able to get firefox to cache the OPTIONS response client side. The other browsers did.
http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js"
var url = 'http://api.example.com/rest/action?key=123ABC&data={"value":55}';
$.ajax({
type: "PUT",
url: url,
data: {},
success: function(msg){
alert( "Data Saved: " + msg );
},
error: function(msg){
console.debug(msg);
}
});

Can AJAX request data from a remote server?

Can I use XMLHttpRequests in JavaScript to request a file on a different server than the one from where the request was made?
Thank you.
You need to use a method that is called as JSONP.
One of the best ways is to use jQuery to reduce the code and worries between your page and the server, and all you need to do is:
$.ajax({
dataType: 'jsonp',
data: 'id=10',
jsonp: 'jsonp_callback',
url: 'http://myotherserver.com/getdata',
success: function () {
// do stuff
},
});
Only if the remote server supports JSONP or HTTP Access-Control headers.
Public JSON API's (like the ones provided by Google.com, Facebook.com, etc) often do.

Categories