简体   繁体   中英

jQuery Ajax Post to php file on an other server is not working

I'am programming a tool, in which you can link my JavaScript file to your website, and this JavaScript file does a ajax post to a PHP file on MY server.

The crazy Thing is that when I link the JavaScript file to a page on my webserver, it works, but when I link the JavaScript file on another website (which has another server) It doesn't works... Here the code:

phpwrite2.php: (The file which should create a file on my server)

<?php

if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
    header('Access-Control-Allow-Origin: *');
    header('Access-Control-Allow-Methods: POST');
    header('Access-Control-Allow-Headers: '.$_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']);
    exit();
}

header('Access-Control-Allow-Origin: *');


$myFile = $_POST['filename'];
$myFile = "users/".$myFile;

chmod("users/",0777);

$fh = fopen($myFile, 'a') or die("can't open file");
$stringData = $_POST["name"];
fwrite($fh, $stringData."\n");
fclose($fh);
?>  

And the jQuery which does the ajax post to the phpwrite2.php file:

function writeToFile() {
    
    $.ajax({
        type: 'POST',
        url: 'http://alexehgm.myhostpoint.ch/phpwrite2.php',
        crossDomain: true,
        data: '{"name":name, "filename" : filename}',
        dataType: 'txt',
        success: function(responseData, textStatus, jqXHR) {
            var value = responseData.someKey;
        },
        error: function (responseData, textStatus, errorThrown) {
            alert('POST failed.');
        }
    });

Thanks for reading my question, I hope you pros know a solution or find the fault.

Basically it comes down to sending the correct CORS headers on OPTIONS request (the preflight request) in addition with a header on the successive requests:

if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
    header('Access-Control-Allow-Origin: *');
    header('Access-Control-Allow-Methods: POST');
    header('Access-Control-Allow-Headers: '.$_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']);
    exit();
}

header('Access-Control-Allow-Origin: *');
// Your code here

Explanation:

  • Acess-Control-Allow-Origin : Sets the Domains that are allowed to access this resource.
  • Acess-Control-Allow-Methods : Sets the HTTP methods that are allowed to access the resource.
  • Access-Control-Allow-Headers : These are the additional headers that are allowed. You can use the requested headers to simply allow all requested. This cannot be * .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM