1

I have a ajax call from a remote site, when i test this on same site it works, when I call it from remote site, I get 200 OK but empty response.

<script type="text/javascript">
function getPage(storename,entries,page) {
    $('#output').html('<div class="centriraj"><span>Loading...</span><img id="loader" src="LoaderIcon.gif" /></div>');
    jQuery.ajax({
        url: "http://jebajiga.byethost32.com/pager.php",
        crossOrigin: true,
        data:'page='+page+'&entries='+entries+'&storename='+storename,
       dataType: "html",
        type: "POST",
        success:function(data){$('#output').html(data);}

    });
}
getPage('cvsstarshop1991',30,1);
</script>
<script type="text/javascript">
function getListCategories(storename) {

    jQuery.ajax({
        url: "http://jebajiga.byethost32.com/categories.php",
        crossOrigin: true,
        data:'storename='+storename,
       dataType: "html",
        type: "POST",
        success:function(data){$('#output2').html(data);}

    });
}
getListCategories('cvsstarshop1991');
</script>
Rohit Gaikwad
  • 817
  • 2
  • 8
  • 24
perkes456
  • 1,163
  • 4
  • 25
  • 49

1 Answers1

1

In order to access data from a remote site using jquery/javascript the remote server must allow CORS. It's a security measure. If the server is yours, add the following into the page header outputs.

 if (isset($_SERVER['HTTP_ORIGIN'])) {
    header("Access-Control-Allow-Origin: {$_SERVER['HTTP_ORIGIN']}");
    header('Access-Control-Allow-Credentials: true');
    header('Access-Control-Max-Age: 86400');    // cache for 1 day
}
if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
    if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_METHOD'])) {
        header("Access-Control-Allow-Methods: GET, POST, OPTIONS");
    }
    if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS'])) {
        header("Access-Control-Allow-Headers: {$_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']}");
    }
    exit(0);
}
sammyukavi
  • 1,501
  • 2
  • 23
  • 51
  • Is this on client side or side where I get data from? And where should I use this code? in php code? – perkes456 Sep 08 '15 at 16:01
  • That code will be helpful if implemented on the serverside – sammyukavi Sep 08 '15 at 16:08
  • I added this piece of code to all remote php scripts.. still same.. "Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://jebajiga.byethost32.com/pager.php. (Reason: CORS header 'Access-Control-Allow-Origin' missing). Line 0" – perkes456 Sep 08 '15 at 16:09
  • 1
    Found a solution.. you were right about this code.. only thing was.. my hosting didnt allowed any header change – perkes456 Sep 09 '15 at 12:19