AJAX Remote Server Step By Step Tutorial - part 2: Imagine your server application retrieve data from other server application. We can provide direct access to that remote server application. But, it will give us more advantage if we provide all access from server ourself. We can build php script on our server that will access the remote server behind of the client. For this job, we can write a script called "proxy server script".
Create a file named "myserver.php" within www/test/ajax. This page will retrieve xml from calc.php (as remote server application). Enter this codes:
<?php
require_once("error_handler.php");
//browser don't cache
header("Expires: Fry, 12 Jan 1990 00:00:00 GMT");
header("Last-Modified: " . gmdate('D, d M Y H:i:s'). ' GMT');
header("Cache-Control: no-cache, must-revalidate");
header("Pragma: no-cache");
//document type
header("Content-type: text/xml");
$param1 = $_GET['param1'];
$param2 = $_GET['param2'];
$func = $_GET['func'];
$serverAddress = "http://localhost/test/ajax/calc.php";
$serverParams = "param1=".$param1."¶m2=".$param2."&func=".$func;
$serverData = file_get_contents($serverAddress. "?" .$serverParams);
echo $serverData;
?>
This page retrieve access to calc.php with code like this:
<?php
set_error_handler('error_handler', E_ALL);
function error_handler($errNo, $errStr, $errFile, $errLine){
if(ob_get_length()) ob_clean();
$error_message = 'ERRNO: ' . $errNo . chr(10).
'TEXT: ' . $errStr . chr(10).
'LOCATION: ' . $errFile .
', line ' .$errLine;
echo $error_message;
exit;
}
?>
Then, modify our "calc.php". Add a line that load the error handler.
<?php
require_once('error_handler.php');
switch($_GET['func']){
case "add":
$result = ($_GET['param1'] + $_GET['param2']);
break;
case "min":
$result = ($_GET['param1'] - $_GET['param2']);
break;
case "div":
$result = ($_GET['param1'] / $_GET['param2']);
break;
case "mul":
$result = ($_GET['param1'] * $_GET['param2']);
break;
}
header('Content-type: text/xml');
$dom = new DOMDocument();
$datas = $dom->createElement('datas');
$dom->appendChild($datas);
$calculation = $dom->createElement('calculation');
$calculationText = $dom->createTextNode($result);
$calculation->appendChild($calculationText);
$datas->appendChild($calculation);
$xmlString = $dom->saveXML();
echo $xmlString;
?>
Next post, we will take action.