JQUERY AJAX GET - CORS Header PHP

210 Views Asked by At

I am trying to write output from PHP script hosted on another domain (HTTPS).

Here is my PHP file:

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

header('Access-Control-Allow-Methods: GET, POST');

header("Access-Control-Allow-Headers: X-Requested-With");

echo "lol";

Here is my HTML code (on another domain):

<script>
var data_from_ajax;

$.get('LINK/script.php', function(data) {
data_from_ajax = data;
});  

document.write(data_from_ajax);

</script>

The later aim is to pass back URL variable and then produce different output.

However, currently - the document.write returns "undefined".

2

There are 2 best solutions below

0
On BEST ANSWER

ur getting "undefined" cause "document.write" is called before the callback.

<!DOCTYPE html>
<html>
    <head>
        <meta name="viewport" content="initial-scale=1.0, user-scalable=no">
        <meta charset="utf-8">
        <script type="text/javascript" src="http://code.jquery.com/jquery-1.11.3.min.js"></script>
    </head>
    <body>

        <!-- Script at the end -->
        <script type="text/javascript" >
            var data_from_ajax = "";

            $.get('script.php', function(response) {
                // This function is called when script.php has responded.
                data_from_ajax = data;

                document.open();
                document.write(data);
                document.close();
            });
        </script>
    </body>
</html>
0
On

Modern browsers (as far as I know) Do now allow ajax request to a different domain to the one you're already on.

Meaning: if you're on www.example.com

your ajax should look

$.get('www.example.com/script.php', function(data) {
    data_from_ajax = data;
});

Other wise you should be getting a warning in your console like: XMLHttpRequest cannot load http://yourdomain.com. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http:///yourdomain.com' is therefore not allowed access.

So what you can do in your case, is from the same domain you're on:

$.get('your-original-domain.com/ajax_handler.php', function(data) {
   data_from_ajax = data;
});

Then with php (or any language for that matter) in the same server

<?php
$data_from_other_server = file_get_contents('https://LINK/script.php');
echo $data_from_other_server;

This way, you're getting the ajax call from your own server, and the info from the other server is being called from yours (and hopefully parsed and sanitized) Before writing to your own page.