[SalesForce] web-to-lead contact form

I've set up a web-to-lead contact form in order to sync contact requests from the website with Salesforce CRM. The sync works fine: the filled fields from the website are showed in the CRM. I need to set up a verification check (all the fields are required). To tho this, I've used a javascript-injected submit. When a user fill the fields and then submit the form, here is the error:

XMLHttpRequest cannot load
https://www.salesforce.com/servlet/servlet.WebToLead?encoding=UTF-8.
No 'Access-Control-Allow-Origin' header is present on the requested
resource. Origin '' is therefore not allowed access.

Origin '' stands for "http://domainname.ext", obviously.

Best Answer

You are hitting the browser's same origin security policy. This means that your JavaScript can only make AJAX calls back to the same origin of the containing page - in this case http://domainname.ext. You are trying to make an AJAX call to Salesforce and that gets blocked.

CORS (cross origin resource sharing) relaxes this restriction by letting servers define which origins are allowed to call them through HTTP headers such as Access-Control-Allow-Origin. However, this is configured on the target server (www.salesforce.com) so Salesforce would need to provide these headers in response to your request, and they don't. Thus your request doesn't succeed and the browser gives you the error.

What is a little confusing about CORS is that you make a request to the server and it will respond with headers to indicate whether the request was allowed or not. The browser then tells you that you can't access that server, but it didn't know until you tried!

Update: See Use CORS to Access Supported Salesforce APIs, Apex REST, and Lightning Out