PHP programming - WebFunction
Frank Yap

WebFunction example is shown in this section.
 

Resources
Lab Exercises
In this section we will show the details of Webfunction.
To show this feature we need to use Javascript and jQuery in addition to PHP. If you are not familiar with those languages just pay attention to the syntax of the code.

Exercise 1: WebFunction demo

Click the refresh button to display images. The button click triggers the WebFunction which fetches new data from the server and updates the screen.

  



 



Let's look at the codes of HTML and WebFunction (Javascript, jQuery and PHP codes) for the above interactive displays.
 
Exercise 2: HTML code


The HTML code looks like below. Each button calls an onClick() function.

&nbsp;&nbsp;<button onClick="buttonRefreshImages()">Refresh</button> 
<br><br><br> 
 
<table style="border-style:solid; width: 600px; height: 200px;"> 
<tr> 
<td id="idImg0"></td> 
<td id="idImg1"></td> 
<td id="idImg2"></td> 
</tr> 
</table> 
 
<br><br><br> 
 
&nbsp;&nbsp;<button onClick="buttonRefreshImages2()">Refresh</button> 
<br><br><br> 
 
<table style="border-style:solid; width: 600px; height: 200px;"> 
<tr> 
<td id="idImgPainter0"></td> 
<td id="idImgPainter1"></td> 
<td id="idImgPainter2"></td> 
</tr> 
<tr> 
<td id="idPainter0"></td> 
<td id="idPainter1"></td> 
<td id="idPainter2"></td> 
</tr> 
</table>
 
Exercise 3: Javascript button click function - WebFunction in client

When the button is clicked it triggers buttonRefreshImages() function. The function looks like below.
In the buttonRefreshImages() function a WebFunction is used to fetch new data. It calls "refreshImages" function and updates the display using the returned data. To send the message to server it uses a jQuery POST method.

The WebFunction parses the returned XML data and extracts the image location URI and sets HTML element so that the browser could fetch the resource and display. To set Document (DOM) element jQuery is used. jQuery is simple and convenient for setting up DOM elements.


<script src="js/jquery.js" type="text/javascript"> 
// This jQuery library should be inserted above any jQuery code. 
</script> 
 
<script type="text/javascript"> 
 
function buttonRefreshImages (){ 
var listImages = new Array(); 
var i = 0; 
var file_name = document.location.href; // current page 
var actionFile = file_name; // let current page handle the ajax processing 
 
// WebFunction 
$.post ( // jQuery post method 
actionFile, 

cmnd:"refreshImages" // function name 
}, 
function(data){ // returned data 
//alert (data); 
var xml = $($.parseXML (data)); 
var status = xml.find("STATUS").text(); 
if (status == "false"){ 
alert ("ERROR occurred"); 
} else { 
i = 0; 
xml.find("IMAGE").each (function(){ 
listImages[i] = $(this).text(); // get value of current tag 
i++; 
});  

 
for (i = 0; i < 3; i++) { 
var strImg = '<img src="'+listImages[i]+'">'; 
$("#idImg"+i).html(strImg); // jQuery DOM manipulation 


); 

</script>

The following is the Javascript code for the second images display.
The difference between the first and second functions is the tag value extractions for the IMAGE tag. In this second function it extracts the values of the child tags of the IMAGE tag.

<script type="text/javascript"> 
 
function buttonRefreshImages2 (){ 
var listImages = new Array(); 
var listPainters = new Array(); 
var i = 0; 
var file_name = document.location.href; // current page 
var actionFile = file_name; // let current page handle the ajax processing 
 
// WebFunction 
$.post ( // jQuery post method 
actionFile, 

cmnd:"refreshImages2" // function name 
}, 
function(data){ // returned data 
//alert (data); 
var xml = $($.parseXML (data)); 
var status = xml.find("STATUS").text(); 
if (status == "false"){ 
alert ("ERROR occurred"); 
} else { 
i = 0; 
xml.find("IMAGE").each (function(){ // extract children's tag 
listImages[i] = $(this).find("FILE_PATH").text(); 
listPainters[i] = $(this).find("PAINTER").text(); 
i++; 
});  

 
for (i = 0; i < 3; i++) { 
var strImg = '<img src="'+listImages[i]+'">'; 
$("#idImgPainter"+i).html(strImg); // jQuery DOM manipulation 
var strPainter = listPainters[i]; 
$("#idPainter"+i).html(strPainter); // jQuery DOM manipulation 


); 

</script>
 

Exercise 4: WebFunction in server

The following is the PHP code which is the other half of the WebFunction.
In the code the glob() function finds the image files and the file paths are packed in the return XML data inside IMAGE tags.
Notice that the IMAGE element is packed into XML differently in the two functions (refreshImages and refreshImages2), and the Javascript side receiving the data has to handle them differently.

<?php       // this portion should be placed before any html output 
if (isset($_POST ['cmnd'])) { 
$postCmnd = $_POST ['cmnd']; 
 
if ($postCmnd == "refreshImages") { 
// handle the ajax processing 
$imgDir = 'images'; 
$str = "$imgDir/{*.jpg,*.jpeg,*.gif,*.png,*.JPG,*.JPEG,*.GIF,*.PNG}"; 
 
$pictures = glob($str, GLOB_BRACE); 
if ($pictures === false) { 
$err = "ERROR: Image file list. "; 
$resp = "<XMLDATA>"."<STATUS>false</STATUS>"."<ERROR>$err</ERROR>"."</XMLDATA>"; 
return; 

$files = count($pictures); 
 
shuffle($pictures); 
$begin = 0; 
$n = $files; 
$xmlList = ""; 
for ($i = $begin; $i < $n; $i++) { 
$xmlList .= "<IMAGE>$pictures[$i]</IMAGE>"; 

 
$resp = "<XMLDATA>"."<STATUS>true</STATUS>"."<IMAGE_LIST>".$xmlList."</IMAGE_LIST></XMLDATA>"; 
echo $resp; 
return; 

 
 
if ($postCmnd == "refreshImages2") { 
// handle the ajax processing 
$imgDir = 'images'; 
$str = "$imgDir/{*.jpg,*.jpeg,*.gif,*.png,*.JPG,*.JPEG,*.GIF,*.PNG}"; 
 
$pictures = glob($str, GLOB_BRACE); 
if ($pictures === false) { 
$err = "ERROR: Image file list. "; 
$resp = "<XMLDATA>"."<STATUS>false</STATUS>"."<ERROR>$err</ERROR>"."</XMLDATA>"; 
return; 

$files = count($pictures); 
 
shuffle($pictures); 
$begin = 0; 
$n = $files; 
$xmlList = ""; 
for ($i = $begin; $i < $n; $i++) { 
$xmlList .= "<IMAGE>"; 
$xmlList .= "<FILE_PATH>$pictures[$i]</FILE_PATH>"; 
$painter = rand (0, $n-1); 
$xmlList .= "<PAINTER>Painter $painter</PAINTER>"; 
$xmlList .= "</IMAGE>"; 

 
$resp = "<XMLDATA>"."<STATUS>true</STATUS>"."<IMAGE_LIST>".$xmlList."</IMAGE_LIST></XMLDATA>"; 
echo $resp; 
return; 

return; 

?>


The above PHP code has to be placed before any HTML text or any other PHP echo outputs. Those outputs will corrupt the function's return values.
 
Homework Exercise

Build a web page where list of cities is displayed as we saw in previous section.
Install a "RefreshList" button to trigger a data fetch and display of the data.
The data fetch function will request a data for a list of cities.
The server will get the data from database we created earlier.
The server will return the list of cities in XML data.
The client that receives the data will parse the data and display on screen.

For the people who are not familiar with Javascript and jQuery, the client side code is provided below (phpLab12_1.php). So your task is on server side fetching data from the database and return the data properly packed in XML so that client could display without modifying the provided code.

Write the server side code on a separate file. The code is provided in phpLab12_2.php with missing parts. You have to complete the code by filling in the missing part.

*** Start XAMPP Apache and MySql servers.
Test the code by running phpLab12_1.php in your browser with the URL http://localhost/phplab/phpLab12_1.php

Verify that everything works, then submit the server file.

Client side codes --------------------------------------------------------------
phpLab12_1.php

HTML page layout (inside phpLab12_1.php):

<!DOCTYPE html> 
<html lang="en"> 
<head><title>PHP Lab 12</title></head> 
<body style="font-family:Verdana; color:#000; font-size:12pt;"> 
 
&nbsp;&nbsp;<button onClick="buttonGetCityList()">Refresh List</button> 
<br><br><br> 
 
<table id="idCityList" style="border-style:solid; width: 600px; height: 200px;"> 
</table> 
 
<!-- Javascript code here --> 
 
</body> 
</html>


Javascript and jQuery code:

<script src="resource/jquery.js" type="text/javascript"> 
// This jQuery library should be inserted above any jQuery code. 
</script> 
 
 
<script type="text/javascript"> 
 
function buttonGetCityList (){ 
//alert ("func called"); 
var listImages = new Array(); 
var listPainters = new Array(); 
var i = 0; 
var file_name = "yourServerFile.php"; // server file 
var actionFile = file_name; // let server file handle the ajax processing 
 
// WebFunction 
$.post ( // jQuery post method 
actionFile, 

cmnd:"getCityList" // function name 
}, 
function(data){ // returned data 
//alert (data); 
var xml = $($.parseXML (data)); 
var status = xml.find("STATUS").text(); 
if (status == "false"){ 
alert ("ERROR occurred"); 
} else { 
var strTable = "<tr><td>City</td><td>Latitude</td><td>Longitude</td></tr>"; 
xml.find("CITY").each (function(){ // extract children's tag 
strTable += "<tr>"; 
strTable += "<td>" + $(this).find("NAME").text() + "</td>"; 
strTable += "<td>" + $(this).find("LATITUDE").text() + "</td>"; 
strTable += "<td>" + $(this).find("LONGITUDE").text() + "</td>"; 
strTable += "</tr>"; 
});  
$("#idCityList").html(strTable); // jQuery DOM manipulation 


); 

</script>


Server side code (phpLab12_2.php). Fill in the missing section.

<?php 
$GLOBALS["host"] = "localhost"; 
$GLOBALS["username"] = "root"; 
$GLOBALS["password"] = ""; 
$GLOBALS["database"] = "cities"; // data base name 
 
 
class CitiesDb { 
 
public function getAllCities () { 
$db = $GLOBALS["database"]; 
$retArr = array ( 
"STATUS" => "true", 
); 
 
$dbConn = @mysql_connect($GLOBALS["host"], $GLOBALS["username"], $GLOBALS["password"]); 
if (!$dbConn) { 
$retArr ["STATUS"] = "false"; 
$retArr ["ERROR"] = "ERROR: DB Connection"; 
return $retArr; 
} else { 
$select_db = @mysql_select_db($db, $dbConn); 
if (!$select_db) { 
$retArr ["STATUS"] = "false"; 
$retArr ["ERROR"] = "ERROR: DB Select"; 
return $retArr; 

 
$tbl = "tbl_cities"; 
 
$sqlStr = "SELECT city, latitude, longitude FROM $tbl"; 
$result = mysql_query($sqlStr, $dbConn); 
if (!$result) { 
$retArr ["STATUS"] = "false"; 
$retArr ["ERROR"] = "ERROR: Invalid Query " . mysql_error(); 
return $retArr; 
} else { 
$retArr ["queryResult"] = $result; 
return $retArr; 



 

 
?> 
 
<?php 
 
if (isset($_POST ['cmnd'])) { 
$postCmnd = $_POST ['cmnd']; 
 
if ($postCmnd == "getCityList") { 
 
$db = new CitiesDb; 
 
// get city list 
$retArr = $db->getAllCities(); 
 
$status = $retArr ["STATUS"]; 
if ($status == "false") { // error 
$err = $retArr ["ERROR"]; 
$resp = "<XMLDATA>"."<STATUS>false</STATUS>"."<ERROR>".$err."</ERROR>"."</XMLDATA>"; 
echo $resp; 
return; 

 
$xmlList = ""; 
$result = $retArr ["queryResult"]; 
while ($row = mysql_fetch_array($result)){ 
$city = $row['city']; 
$latitude = $row['latitude']; 
$longitude = $row['longitude']; 
 
// fill in code here 
// ... 
// ... 
// ... 

 
$resp = "<XMLDATA>"."<STATUS>true</STATUS>"."<CITY_LIST>".$xmlList."</CITY_LIST></XMLDATA>"; 
echo $resp; 
return; 
 


?>