0

I cant understand how can I enable CORS while using Ajax to send information to a remote server located on another domain. I read a lot about that and many other questions on Stackoverflow but something just doesnt add up. I know that in order to bypass the security check of the browser I need to add a Access-Control-Allow-Origin: * header to my code, but where exactly? I know there is another option to add this header as a simple tag in a PHP file and then create a POST message using curls, but I'm not proficient with PHP as I am with JS. Can someone help me understand how should this be done? Important to say, I cant configure or change the servers settings, so everything must be done in the client side.

This is my code so far. I managed to get this message through using Chrome plugin, but obviously this isn't good enough since I cant recreate what the plugin is doing.

$.ajax({ type: "POST", url: "someURL", data: {name: "John", lastName : "Johnson", state : "NYC" }, headers: { "Access-Control-Allow-Origin: *" } }) .done(function( msg ) { console.log(msg); }); 
1
  • No change possible on the server = no CORS. You need to have permission from the remote server to post ajax requests. Commented Dec 29, 2014 at 21:01

2 Answers 2

1

You don't have to do this. The browser is smart enough to figure out what headers are needed. Indeed, that is the point: the browser has detected the cross-site-scripting issue and is asking the server if it is OK to proceed.

You may need to tweak your server-side code to respond to the headers properly.

Sign up to request clarification or add additional context in comments.

Comments

0

Access-Control-Allow-Origin is a response header. The server you are making the request to has to include it to give your JavaScript permission to read the data.

I cant configure or change the servers settings, so everything must be done in the client side.

Your JavaScript cannot give itself permission to read data from other sites.

You will need to use a proxy to fetch the data.

2 Comments

Thanks for the answer. So how does the Chrome plugin is able to give my code the permission to read\send data from the remote server? edit - the plugin uses proxy as well?
A Chrome Extension is not some untrusted JavaScript running on a webpage the browser's owner is visiting. It is a piece of installed software (and it has to ask for permission from the browser owner to access other sites when it is installed) so it is not subject to the Same Origin Policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.