I am trying to make a program that grabs all the links from an external website and display them using jQuery and PHP. Here are my steps:
- Get the html of a page using php (load.php)
- Put that html into a div
- Get all elements in that div
Here is my code (index.html):
<html>
<head>
<title>Test</title>
<script type="text/javascript" src="jquery.js">//jquery</script>
<script type="text/javascript">
$(function() { //on load
var url = "http://google.com";
$.post('load.php', { url: url},
function(html) {
$('#page').html(html); //loads html from the page into a div
var links = $('#page > a');
alert('links.length: ' + links.length); //PROBLEM: returns 0
for(var i=0; i < links.length; i++)
{
alert(links[i]);
}
});
});
</script>
</head>
<body>
<div id="page" style=""></div>
</body>
</html>
And the php code (load.php):
<?php
$url = $_POST['url'];
$html = file_get_contents($url);
echo $html;
?>
The page is being loaded into the div correctly, so I know it is grabbing the html, but links.length is returning 0. So it is something wrong with this line:
var links = $('#page > a');
However, when I try to load it on my test page with html:
<a href="http://google.com">link1</a>
<a href="http://yahoo.com">link2</a>
links.length
returns 2. Why does it work with my test page and not google?