1

I'd like to post data from domain1.com to domain2.com using AJAX, but my request fails.

Here's is my code on domain1.com:

$.ajax({
    type: 'POST',
    url: 'https://domain2.com/payment/api/server',
    crossDomain: true,
    data: {
            Name: $("#name").val().trim(), 
            Email: $("#email").val().trim()
          },
    dataType: 'json',
    success: function(data) {
        alert('Success');
    },
    error: function (data) {
        alert('POST failed.');
    }
});

and here's my server side code on domain2.com:

switch ($_SERVER['HTTP_ORIGIN']) {
  case 'http://domain1.com/api/': case 'http://domain1.com/api/':
    header('Access-Control-Allow-Origin: '.$_SERVER['HTTP_ORIGIN']);
    header('Access-Control-Allow-Methods: GET, PUT, POST, DELETE, OPTIONS');
    header('Access-Control-Max-Age: 1000');
    header('Access-Control-Allow-Headers: Content-Type, Authorization, X-Requested-With');
  break;
}

$name = $_POST['Name'];

echo $name; // Just to check if I receive the value from index.php
Michał Perłakowski
  • 88,409
  • 26
  • 156
  • 177
PHP4lite
  • 31
  • 6
  • The answer on the duplicate is outdated. Nowadays we have CORS: http://stackoverflow.com/questions/10636611/how-does-access-control-allow-origin-header-work – Arnold Daniels Jan 24 '16 at 03:28
  • 1
    **Marked for reopening.* The OP asks about cross domain post using CORS. The other question and selected answer don't mention CORS. – Arnold Daniels Jan 24 '16 at 03:33
  • @Jasny-ArnoldDaniels is there any wrong with the given code? please advise. – PHP4lite Jan 24 '16 at 11:49

2 Answers2

1

You are checking if Origin HTTP header equals to 'http://domain1.com/api/'. However, MDN CORS docs say:

The origin is a URI indicating the server from which the request initiated. It does not include any path information, but only the server name.

You have to remove the path from the string, i.e. it has to be 'http://domain1.com'.

Corrected server.php code:

switch ($_SERVER['HTTP_ORIGIN']) {
  case 'http://domain1.com':
    header('Access-Control-Allow-Origin: '.$_SERVER['HTTP_ORIGIN']);
    header('Access-Control-Allow-Methods: GET, PUT, POST, DELETE, OPTIONS');
    header('Access-Control-Max-Age: 1000');
    header('Access-Control-Allow-Headers: Content-Type, Authorization, X-Requested-With');
  break;
}

$name = $_POST['Name'];

echo $name;
Michał Perłakowski
  • 88,409
  • 26
  • 156
  • 177
-1

As a side note: if you are using the "HTTP_ORIGIN" header to "secure" your requests, you should rethink it. Anyone can spoof this header and arbitrarily set the value. You are better off using some kind of key/secret to avoid unwanted requests. See: Is CORS a secure way to do cross-domain AJAX requests?

Community
  • 1
  • 1
diego nunes
  • 2,750
  • 1
  • 14
  • 16