If you’re looking for the quickest way to get your PHP functionality Ajax enabled, you’ve got to take a look at PHPLiveX. It greatly simplifies the process of Ajaxifying your PHP code without knowing Javascript code.
Let’s see how to Ajaxify a simple PHP function. Let’s create a simple function to output the server time:
function myServerTime(){
return date("D M j G:i:s T Y");
} |
First you have to include the PHPLiveX library and register your function. Here’s how to to it:
<? php
include 'PHPLiveX.php';
function myServerTime(){
return date("D M j G:i:s T Y");
}
$phplive = new PHPLiveX("myServerTime"); //Register the function with PHPLiveX
?> |
$phplive = new PHPLiveX(“myServerTime”); is used to register our function myServerTime with PHPLiveX
Next let’s build our HTML Display. Let’s keep it simple, but allowing the user to click a link to get the updated server time:
<a href="">Get Server Time </a> |
Now we’ll have to create areas to display our Loading Status and the results back from the server. Let’s create two divs for this.
<span id="loading" style="visibility:hidden">Loading...</span>
<span id="serverResult" style='clear:both;'></span> |
You’ll notice that the loading span’s visibility has been set to hidden by default. PHPLiveX will use this to show the loading indicator when an action is being performed.
Now let’s get the entire HTML created. PHPLiveX autogenerates the Javascript required to create the AJAX calls, this has to take place in the html head section. To generate the Javascript all you need to call is $phplive->Run(). So let’s get to the entire script with the HTML:
<? php
include 'PHPLiveX.php';
function myServerTime(){
return date("D M j G:i:s T Y");
}
$phplive = new PHPLiveX("myServerTime"); //Register the function with PHPLiveX
?>
<html>
<head>
<title>My Ajax Server Time</title>
<script>
<?php
$phplive->Run();
?>
</script>
</head>
<body>
<a href="javascript:myServerTime('', 'target=serverResult,preload=loading');">Get Server Time</a>
<span id="loading" style="visibility:hidden">Loading...</span>
<span id="serverResult"></span>
</body>
</html> |
You’ll notice that in the Get Server Time link there’s a little bit of Javascript – javascript:myServerTime(”, ‘target=serverResult,preload=loading’);. That’s used to call the myServerTime function from Javascript. The first parameter is null since our function myServerTime doesn’t accept any parameters. The second parameter tells PHPLiveX to send the output to the “serverResult” div and use the “loading” div as the preloader.
That’s it ! You can see a demo of this here.
Get the source code for this tutorial here. This includes version 2.2 of the PHPLiveX library.
I’ll put up a tutorial on how to use PHPLiveX for a whois lookup next week.
Link to PHPLiveX: PHPLiveX -> An Open Source PHP/Ajax Library