0

To start off JS is NOT my strong suite. What I am trying to do is run some code between 2 sites. So for example we have site A, and site B.

Site B contains a file called auth.js which the content is below.

function  test() {
alert("bingo");
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
        // document.getElementById("demo").innerHTML = this.responseText;
        alert( this.responseText );
    }
};
xhttp.open("POST", "https://siteb.com/auth.php", true);
xhttp.send();
};

Now inside site A I am including auth.js and running the function test()

As of now I am getting the alert message fine, however I'm receiving a console message about CORS (which i googled a bit and it doesn't make sense to me).

All of the code is living on site B. I'm wanting to run a php script when this js file is called, then output the data back as javascript on site A. So my php script will do all of the authentication and structure new js code and echo it out.

What am I missing to make CORS work properly?

Thanks in advance.

joeb
  • 777
  • 8
  • 28

2 Answers2

1

ok so finally got some code to work for me. Heres what I did.

inside auth.php on Site B I've added the following lines of code.

header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST');
header('Access-Control-Max-Age: 1000');
header('Access-Control-Allow-Headers: Content-Type, Authorization, X-Requested-With');

Right now this is allowing all traffic to come through. If you want to restrict it to a specific domain, then swith the * to http://example.com

and also modified the file auth.js on Site B

function  test() {
alert("bingo");

$.ajax({
    type: 'POST',
    url: 'https://siteb.com/auth.php',
    crossDomain: true,
    data: {},
    async: false,
    success: function(response) {
        alert(response);
    },
    error: function (jqXHR, textStatus, errorThrown) {
        alert(errorThrown);
        alert(textStatus);
    }
});
};

so now on site A. I'm calling only test();

hope this helps someone else

joeb
  • 777
  • 8
  • 28
0

Make a PHP file which will send the request in PHP CURL, gets the response and sends that response to the browser. Instead of sending a request from Javascript to the final target, send this to your own server and make sure your PHP is being executed. This should resolve the CORS issue. Other potential problems will be that you will have to make sure that the script, link, a, img tags have proper path.

Lajos Arpad
  • 64,414
  • 37
  • 100
  • 175