Tuesday 12 October 2010

Put external web content into your page using jQuery and PHP

I looked into using the jQuery .load and .get methods to do this, but it only seemed to work with content on my server. I knew that PHP had a really good function called file_get_contents, so I thought, I'll use that, but jQuery is still good for putting the contents into your page. Here is an example of how they work together to achieve the goal.

See demo.

First the HTML file :

<!DOCTYPE html>
<html lang=”en”>
<head>
<meta charset="UTF-8">
<title>jQuery Loading External Content</title>
<style type="text/css">
body
{
font-family:Sans-serif;
}
#container
{
background:#FF0000;
color:#FFFFFF;
width:400px;
height:400px;
}
</style>
<script src="http://www.google.com/jsapi"></script>
<script>
google.load("jquery", "1");
google.load("jqueryui", "1");
</script>
<script>
$(document).ready(function()
{
    $('a').click(function()
    {
        $.post("getTheContent.php",
        {
theAddress:$(this).attr('url')
        }, function(data)
        {
/* This is where you would manipulate the data before it is pushed into the div */
$('#container').html(data);
console.log(data);
        });
        return false;
    });
});
</script>
</head>
<body>
<a url="http://htmldog.com/examples/textalign.html">first</a>
<a url="http://htmldog.com/examples/headings1.html">second</a>
<a url="http://htmldog.com/examples/superscript.html">third</a>
<a url="http://htmldog.com/examples/case.html">fourth</a>
<div id="container">

</div>
</body>
</html>

Now, the PHP file called getTheContent.php :

<?php
    echo file_get_contents($_POST["theAddress"]);
?>

You can see that I am posting the value of the url descriptor from the anchor tag to the PHP file using jQuery. Then I echo the results back into jQuery and push it into the div.

No comments:

Post a Comment