AJAX and PHP
You also want an ePaper? Increase the reach of your titles
YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.
Server-Side Techniques with <strong>PHP</strong> <strong>and</strong> MySQL<br />
The error-h<strong>and</strong>ling scheme presented is indeed quite simplistic, <strong>and</strong> it is only appropriate<br />
while writing <strong>and</strong> debugging your code. In a production solution, you need to show your<br />
end user a friendly message without any technical details. If you want to package the<br />
error details as an XML document to be read on the client, keep in mind that parse <strong>and</strong><br />
fatal errors will not be processed by your function, <strong>and</strong> will behave as set up in <strong>PHP</strong>'s<br />
configuration file (php.ini).<br />
This case also presents the scenario where the user can attempt to make several server requests at<br />
the same time (you can do this by clicking the Send button multiple times quickly enough). If you<br />
try to make a request on a busy XMLHttpRequest object, its open method generates an exception.<br />
The code is well protected with try/catch constructs, but the error message doesn't look very<br />
user-friendly as shown in Figure 3.6.<br />
Figure 3.6: Request on a Busy XMLHttpRequest<br />
This message might be just what you need, but in certain circumstances you may prefer to react<br />
differently to this kind of error than with other kinds of errors. For example, in a production<br />
scenario, you may prefer to display a note on the page, or display a friendly "please try again<br />
later" message, by modifying the process() function as shown in the following code snippet:<br />
// read a file from the server<br />
function process()<br />
{<br />
// only continue if xmlHttp isn't void<br />
if (!xmlHttp) return;<br />
// don't try to make server requests if the XMLHttpObject is busy<br />
if !(xmlHttp.readyState == 0 || xmlHttp.readyState == 4)<br />
alert("Can't connect to server, please try again later.");<br />
else<br />
{<br />
// try to connect to the server<br />
try<br />
{<br />
// get the two values entered by the user<br />
var firstNumber = document.getElementById("firstNumber").value;<br />
var secondNumber = document.getElementById("secondNumber").value;<br />
// create the params string<br />
var params = "firstNumber=" + firstNumber +<br />
"&secondNumber=" + secondNumber;<br />
// initiate the asynchronous HTTP request<br />
xmlHttp.open("GET", "morephp.php?" + params, true);<br />
xmlHttp.onreadystatechange = h<strong>and</strong>leRequestStateChange;<br />
xmlHttp.send(null);<br />
}<br />
78<br />
www.it-ebooks.info