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?
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/");
?>
Out of the box: no. It's a security issue. There are a few different workarounds though.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With