通过邮件跨站点HTTP

Trying to send data to a different domain. I am currently working on localhost.

I tried to keep it as simple as possible for now

js:

window.onbeforeunload = function() {

    var url = "http://localhost/web/x/boot/ajax/x.php?";
    $.post(url, { thing: "value" }, function(data) {});
};

Chrome shows this request in the Developer Tools > Timeline as:

   Self Time: 0
   Start Time: 6 ms
   Resource: localhost/web/x/boot/ajax/x.php?
   Request Method: POST
   Call Stack:
   send @ jquery.min.js:4
   m.extend.ajax @ jquery.min.js:4
   m.(anonymous function) @ jquery.min.js:4
   window.onbeforeunload @ x.js:249

and my most simple php file to record any loading:

<?php
   //include 'config.php';

    $handle = fopen('temp.txt','w') or die('Cannot open file:  ');
        fwrite($handle, 'hit');
        fclose($handle);
    exit();
?>

The file doesn't get hit for some reason. If I copy the url from the Chrome request above and paste it in, that works.

Does the PHP file it's hitting need all the normal HTML tags etc? Could that be the issue?


Update

$.post(url,{},function(res){
        alert('successful');
   }).error(function(xhr,textStatus,error){
           alert(xhr.statusText + "
" + textStatus + "
" + error +"." );
          });

Returns an error:

 <blank>
 error
 error
 .

Got it. Not using jQuery, post, or ajax. Returning to javascript to make a HTTP request. I do not want to load the data on the webpage. I am actually sending data when the user leaves the page.

The following hits and creates the file I've mentioned above

window.onbeforeunload = function() {
   //...  create params
    var XHR = new XMLHttpRequest();
    XHR.open('POST', "http://localhost/web/x/boot/ajax/x.php?", false);
    //XHR.open('POST', "http://127.0.0.1/web/x/boot/ajax/x.php?", false); // also works
    //XHR.open('POST', "http://{ip-address}/web/x/boot/ajax/x.php?", false); // also works
    XHR.send(params);
}

Params are being sent. Just gotta figure out how to deal with it now :p

Thanks anyways!

window.onbeforeunload: your request probably killed by the browser before it gets done when window is closed.

For testing Cross Domain in Localhost you can use your ip address like 192.168.0.1 for making request.

    window.onbeforeunload = function() {
        var url = "http://{ip-address-here}/web/x/boot/ajax/x.php?";
        $.post(url, { thing: "value" }, function(data) {});
    };

Check same call from other machine.