Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery load external site page

Tags:

jquery

load

Is it possible to load a single page from an external website?

I am trying to show up a single page but cannot seem to get it to work

$("#response").load("http://domain.com", function(response, status, xhr) {
   if (status == "error") {
      var msg = "Sorry but there was an error: ";
      alert(msg + xhr.status + " " + xhr.statusText);
   }
 });

Help would be greatly appreciated

like image 711
ngplayground Avatar asked Feb 21 '13 10:02

ngplayground


2 Answers

Are you trying to load a page on a different domain?

If yes, then it seems you got a cross-domain policy on your way...

like image 128
andri Avatar answered Jan 12 '23 10:01

andri


You're running into a cross domain policy issue cause AJAX (for security reasons) will not let you grab content from a page that does not sit on the same domain.

To get rid of it and accomplish your task:
you need a PHP file you can call grabber.php with just this line of PHP:

<?php echo file_get_contents($_GET['url']); ?>

Than inside your html (or whatever file just do like:)

<!DOCTYPE html>
<html>
<head>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
    <meta charset=utf-8 />
    <title>test</title>
</head>
<body>

    <div id="response"></div>

</body>

<script>
$(function(){
    var contentURI= 'http://domain.com #element';    // URL TO GRAB + # of any desired element // if needed :)
    $('#response').load('grabber.php?url='+ contentURI);
});
</script>

</html>

Why does this work?

  • now, AJAX is sending a simple GET request to the grabber.php page,
  • grabber.php echoes the desired content
  • now the content is on your (server) domain!
  • and AJAX is happy to serve you :)
like image 29
Roko C. Buljan Avatar answered Jan 12 '23 10:01

Roko C. Buljan