-2

I am trying to post data with ajax to an external url with the following code:

$(document).ready(function(){
    $('.submit_button').click(function() {
        $.ajax({
                type : 'POST',
                url : 'http://site.com/post.php',
                dataType : 'text',
                data: $("#infoForm").serialize()
        }).done(function(results) {
                    alert(results);
        });
        event.preventDefault();
    });
});

But I am getting the following error:

XMLHttpRequest cannot load http://site.com/post.php. Origin null is not allowed by Access-Control-Allow-Origin.

I have also added the the following line to the htaccess file on my server

Header set Access-Control-Allow-Origin *

Would anyone be able to tell me what I am doing wrong and how I can post data to an external url?

Daniil
  • 43
  • 1
  • 1
  • 8
  • Related post with the answer you want: http://stackoverflow.com/questions/3988080/jquery-post-to-external-php?rq=1 – StoicJester May 09 '13 at 15:12
  • "*what I am doing wrong*" your posting to a cross-origin server with a browser, which isn't allowed without proper CORS headers. *"how I can post data to an external url"* use CORS, but know that it isn't supported in IE7 and jQuery does not implement it properly in IE8 or IE9, so you'll have to do it without jQuery, or extend jQuery. – Kevin B May 09 '13 at 15:12
  • 2
    And you could'nt search for that error message, and find one of the other gazillion questions regarding javascripts same-origin policy ? – adeneo May 09 '13 at 15:13

2 Answers2

3

Is the external URL yours? If no, it's not possible. If yes you have to return the following headers on that domain:

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

Or if you want to allow all domains:

Access-Control-Allow-Origin: *

More info can be found here: https://developer.mozilla.org/en-US/docs/HTTP/Access_control_CORS

If it's not your domain you have to create a proxy, create a PHP file that gets the content you need from that domain. And do your ajax request to your own domain.

Niels
  • 48,601
  • 4
  • 62
  • 81
  • I forgot to mention that I have tried to add the headers to the .htaccess file, but they didn't work. I just modified the .htaccess to: Header set Access-Control-Allow-Origin "*" And that seems to work, thanks for your help guys! – Daniil May 09 '13 at 15:28
0

You cannot use Ajax to send requests to another domain, unless you make use of CORS. This is due to the same-origin policy. If you own the server, you can set up CORS in Apache by making an .htaccess file with the contents Access-Control-Allow-Origin: *

Stephen K
  • 697
  • 9
  • 26
  • You shouldn't assume everyone is using Apache, only half of all websites use it as a web server. One in five readers are probably using Nginx, for example. – MattWithoos Nov 26 '14 at 03:55