Simple Ajax , Populate div with data from php file.

Heres a quick and dirty lowdown on how to populate a div with some data from a php file.

OK,
Lets say you have a php file called helloworld.php
And it contained:

1
2
3
<?php
echo "Hello World!!!!";
?>

Now, if you run this php file it will be a nice white page with just hello world in it.
What if you had a really cool website and wanted this data in a div on your website but you dont want to use frames etc.

Well, We can use Ajax to call your php script and then put any output from that script into any div you want on your webpage.

Ok,
So on your html page put this code in:

1
2
3
4
5
6
7
8
9
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3/jquery.min.js"></script>
 
<script language="javascript" type="text/javascript">
<!--
function getdata() {
$('#JEFF').load('helloworld.php');
}
//-->
</script>

The above will call the google Ajax library and create a function we can use to populate our div ( In this case the div will be called JEFF )

Whenever you call that javascript function it will now populate a div named JEFF with the output of helloworld.php

1
2
<div id="JEFF">Output will appear here</div>
<a href="javascript:getdata();">ClickMe</a>

You could use a javascript timer to call the php script an dupdate the div as often as you want, Or have it update on a link click..

Done.

Comments are closed.