Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I load data from an external page via AJAX?

I've just starting learning jQuery and AJAX. I'm able to load a local page (on my disk) into a div via jQuery.load(), but external sites don't seem to work. I've even used wireshark to check if the data is being sent from the server (it is). Sample code is below:

<html>
<head>
    <script src='jquery-1.4.2.min.js'></script>
    <script>
        $(document).ready(function() {
            // $('#test').load('localpage.htm'); works!
            $('#test').load('http://www.google.com/'); // does not work!
        });
    </script>
</head>
<body>
<div id='test'></div>
</body>
</html>

Is it possible to do this in the first place? If so, how?

like image 838
int3 Avatar asked Mar 09 '10 14:03

int3


3 Answers

You cannot do ajax calls to a different domain than the script originates from.

For doing such a thing, you have to use a proxy page on your own page, eg:

<script>
    $(document).ready(function() {
        $('#test').load('ajax/getgoogle.php');
    });
</script>

getgoogle.php:

<?php

echo file_get_contents("http://www.google.com/");

?>
like image 137
Phil Rykoff Avatar answered Nov 08 '22 03:11

Phil Rykoff


Out of the box: no. It's a security issue. There are a few different workarounds though.

like image 3
Hooray Im Helping Avatar answered Nov 08 '22 05:11

Hooray Im Helping


You're running into the Same Origin Policy. You can't access data from an external domain using AJAX, it's considered a security risk. The reasoning behind it is that AJAX requests work with cookies stored by the browser -- if I tried to access facebook.com, and you were logged in there, the cookie would be sent and I'd have access to your personal data.

like image 2
Andy E Avatar answered Nov 08 '22 05:11

Andy E