tags:

views:

65

answers:

4

hey guys, is it possible to load a foreign website into a div of my page with the jQuery load method?

$('#content').load('http://www.somedomain.com/server/whatever/file.php');

it's not working for me!

regards matt

+2  A: 

From the jQuery.load page:

Due to browser security restrictions, most "Ajax" requests are subject to the same origin policy; the request can not successfully retrieve data from a different domain, subdomain, or protocol.

Same origin policy

Giorgi
+1  A: 

You can't due to security restrictions in the browser. Use a proxy.

http://developer.yahoo.com/javascript/howto-proxy.html

Peter Forss
+2  A: 

As @Giorgi says, cross site calls are often blocked due to security restrictions. However, if the remote site returns JSONP the call will most likely work.

For other calls you have to call on a page on your own site. And that page could veru well be a proxy which fetches the requested url on the backend instead.

$('#content').load('/myproxy.handler?url=http://www.somedomain.com/server/whatever/file.php');
Mikael Svenson
For security reasons (XSS for example) I don't think a generic proxy is a good solution. This might be a better solution:/myproxy.handler?action=GetWhateverData and then the proxy handler knows the URL:
Peter Forss
is it possible to use jquery load with a SUBDOMAIN of the same URL? if the load fires on http://www.mydomain.com can i load http://hello.mydomain.com/hello.php ???
It's possible, and it involves setting document.domain = "yourdomain.com". See http://www.tomhoppe.com/index.php/2008/03/cross-sub-domain-javascript-ajax-iframe-etc/ for more information and sample.
Mikael Svenson
A: 

You might be able to work around the security restriction described by @Giorgi using a PHP-based proxy script.

proxy.php

<?php
if( isset( $_GET['url'] ) ) {
 # Get the Referred URL
  $raw = file_get_contents( $_GET['url'] );
 # RegExp to Strip All Script tags and/or links with Javascript in them.
  $safe = preg_replace( '/<script[^>]*>.*<\/script>|[\"\']javascript:.*[\"\']/im' , '' , $raw );
  echo $safe;
} else {
  echo 'No URL Set';
}

Then use the jQuery load action to call pages like proxy.php?url=http%3A//www.google.com/

Not, the preg_replace() action is just a rough draft - you would want to do some major testing and tweaking to ensure that you prevent people from messing with your site this way.

Lucanos
what do you mean by messing with my site?
Cross-site Scripting - http://en.wikipedia.org/wiki/Cross-site_scripting. Where javascript, within the third-party page you are calling, can be triggered as though it was from your site, potentially compromising security.
Lucanos