370 likes | 514 Views
PHP and AJAX. ISYS 475. AJAX. Asynchronous JavaScript and XML : JavaScript, Document Object Model, Cascade Style Sheet, XML, server-side script such as . Net , PHP, etc. Partial refresh: It lets you update part of a web page without having to reload the entire page.
E N D
PHP and AJAX ISYS 475
AJAX • Asynchronous JavaScript and XML: • JavaScript, Document Object Model, Cascade Style Sheet, XML, server-side script such as .Net, PHP, etc. • Partial refresh: It lets you update part of a web page without having to reload the entire page. • RIA: Rich Internet Application • Quick response time, interactive page
How AJAX Updates a Page • When an event happens, JavaScript (AJAX engine) prepares a request and sends it to the web server. • The server receives the request and processes it. • The server prepares a response and sends it back to the browser. • The JavaScript parses the response to update the page.
XMLHTTPRequestJavascript object • Update a web page without reloading the page • Request data from a server after the page has loaded • Receive data from a server after the page has loaded
Creating a XMLHttpRequest Object if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari xmlhttp=new XMLHttpRequest(); } else {// code for IE6, IE5 xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); }
The Open Methods of XMLHTTPRequest object • The HTTP and HTTPS requests of the XMLHttpRequest object must be initialized through the open method. There 5 parameters, but 2 are enough: • open( Method, URL, Asynchronous, UserName, Password ) • Method: GET, POST • URL: the URL of the HTTP request • Asynchronous: true/false; default is true • Example: • xmlhttp.open('GET', 'http://localhost:8000/demoPHPAjax.php', true);
The send method • This method accepts a single parameter containing the content to be sent with the request. This parameter may be omitted if no content needs to be sent. • send( Data )
The onreadystatechange event listener • For an asynchronous request, the onreadystatechange event listener will be automatically invoked for each of the following actions that change the readyState property of the XMLHttpRequest object.
The Four ReadyStates • After the open method has been invoked successfully, the readyState property of the XMLHttpRequest object should be assigned a value of 1. • After the send method has been invoked and the HTTP response headers have been received, the readyState property of the XMLHttpRequest object should be assigned a value of 2. • Once the HTTP response content begins to load, the readyState property of the XMLHttpRequest object should be assigned a value of 3. • Once the HTTP response content has finished loading, the readyState property of the XMLHttpRequest object should be assigned a value of 4.
Example xmlhttp.onreadystatechange = function() { if (xmlhttp.readyState === 4){ alert(xmlhttp.readyState); } }; xmlhttp.open('GET', 'somepage.xml', true); xmlhttp.send(null); Note 1: The listener must be defined before the open method is invoked. The open method must be invoked before the send method is invoked. Note 2: Three “=“ : (xmlhttp.readyState=== 4)
The responseXML property and responseText • After a successful and completed call to the send method of the XMLHttpRequest, if the server response was valid XML and the Content-Type header sent by the server is understood by the user agent as an Internet media type for XML, the responseXML property of the XMLHttpRequest object will contain a DOM document object. Another property, responseText will contain the response of the server in plain text by a conforming user agent, regardless of whether or not it was understood as XML.
Overall Processes • Create an XMLHttpRequest object • Create the function to be executed when the server response is ready • Send the request off to a file on the server • Insert the response from the server to the web page
Example: HTML Page <head> <title></title> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <script> function MakeRequest() { if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari xmlhttp=new XMLHttpRequest(); } else {// code for IE6, IE5 xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); } xmlhttp.onreadystatechange = function() { if (xmlhttp.readyState===4){ document.getElementById('ResponseDiv').innerHTML = xmlhttp.responseText; } } xmlhttp.open('GET', 'http://localhost:8000/demoPHPAjax.php', true); xmlhttp.send(null); } </script> </head> <body> <input type='button' onclick='MakeRequest();' value='Use AJAX!!!!'/> <div id='ResponseDiv'> This is a div to hold the response. </div> </body> </html>
Example: PHP Page <?php echo "This is a php response to your request!!!!!!"; ?>
JavaScript to compute the future value:No protection of source code
Using document.getElementById <form name="fvForm"> Enter PV: <input type="text" id ="PV" name="PV" value="" size="10" /><br> <select name="Rate" id="Rate"> <option value=".04">4%</option> <option value=".05">5%</option> <option value=".06">6%</option> <option value=".07">7%</option> <option value=".08">8%</option> </select><br> Select Year: <br> <input type="radio" name="Year" value=10 id="Year10" />10 year<br> <input type="radio" name="Year" value=15 id="Year15" />15 year<br> <input type="radio" name="Year" value=30 id="Year30" />30 year<br> <br> Future Value: <input type="text" name="FV" /> <br> <input type="button" value="ComputeFV" name="btnCompute" onClick="ComputeFV()" />
function ComputeFV(){ //myPV=eval(document.fvForm.PV.value); myPV=parseFloat(document.getElementById("PV").value); myRate=parseFloat(document.getElementById("Rate").value); if (document.getElementById("Year10").checked) {myYear=10;} else if (document.getElementById("Year15").checked) {myYear=15;} else {myYear=30;} fv=myPV*Math.pow(1+myRate,myYear); document.fvForm.FV.value=fv.toString(); }
Display future value with the inputs, fvForm2.php: Page reloaded everytime <?php if (!empty($_POST)){ $myPV=$_POST["PV"]; $myRate=$_POST["Rate"]; $myYear=$_POST["Year"]; $FV=$myPV*pow(1+$myRate,$myYear); echo "<form name='fvForm' method='post' action='fvForm2.php'>"; echo "Enter present value: <input type='text' name='PV' value='$myPV' /><br><br>"; echo "Select interest rate: <select name='Rate'>"; for ($v=.04; $v<=.08;$v+=.01){ $display=$v*100; if ($v==$myRate) echo "<option selected value=$v>$display%</option>"; else echo "<option value=$v>$display%</option>"; } echo "</select><br><br>"; echo "Select year: <br>"; for ($v=10; $v<=30;$v+=10){ $display=$v . '-year'; if ($v==$myYear) echo "<input type='radio' name='Year' checked value='$v' />$display<br>"; else echo "<input type='radio' name='Year' value='$v' />$display<br>"; } $CFV="$" . number_format($FV,2); echo "Future value is :<input type='text' name='FV' value='$CFV' /><br><br>"; echo "<input type='submit' value='ComputeFV' name='btnCompute' />"; } else { ?> <form name="fvForm" method="post" action="fvForm2.php"> Enter present value: <input type="text" name="PV" value="" /><br><br> Select interest rate: <select name="Rate"> <option value=.04>4%</option> <option value=.05>5%</option> <option value=.06>6%</option> <option value=.07>7%</option> <option value=.08>8%</option> </select><br><br> Select year: <br> <input type="radio" name="Year" value="10" />10-year<br> <input type="radio" name="Year" value="20" />20-year<br> <input type="radio" name="Year" value="30" />30-year<br><br> Future value is :<input type="text" name="FV" value="" /><br><br> <input type="submit" value="ComputeFV" name="btnCompute" /> <?php } ?> </form>
Using AJAX to compute FV <script> function ComputeFV(){ myPV=parseFloat(document.getElementById("PV").value); myRate=parseFloat(document.getElementById("Rate").value); if (document.getElementById("Year10").checked) {myYear=10;} else if (document.getElementById("Year15").checked) {myYear=15;} else {myYear=30;} if (window.XMLHttpRequest) xmlhttp=new XMLHttpRequest(); else xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); xmlhttp.onreadystatechange = function() { if (xmlhttp.readyState === 4){ document.getElementById("FV").value = xmlhttp.responseText; } }; xmlhttp.open('GET', 'computeFV.php?pv='+ myPV + '&rate=' + myRate + '&year=' + myYear , true); xmlhttp.send(null); } </script>
<form name="fvForm"> Enter PV: <input type="text" id ="PV" name="PV" value="" size="10" /><br> <select name="Rate" id="Rate"> <option value=".04">4%</option> <option value=".05">5%</option> <option value=".06">6%</option> <option value=".07">7%</option> <option value=".08">8%</option> </select><br> Select Year: <br> <input type="radio" name="Year" value=10 id="Year10" />10 year<br> <input type="radio" name="Year" value=15 id="Year15" />15 year<br> <input type="radio" name="Year" value=30 id="Year30" />30 year<br> <br> Future Value: <input type="text" id="FV" name="FV" /> <br> <input type="button" value="ComputeFV" name="btnCompute" onClick="ComputeFV()" /> </form>
The PHP file <?php $pv=$_GET["pv"]; $rate=$_GET["rate"]; $year=$_GET["year"]; $fv=$pv*pow(1+$rate,$year); echo $fv; ?>
Loan calculation: Server determines rate based on loan, term, credit passed to PHP by AJAX
Passing loan, term, credit to PHP by AJAX <script> function computeLoan(){ loan=parseFloat(document.loanForm.loan.value); term=parseFloat(document.loanForm.term.options[document.loanForm.term.selectedIndex].value); if (document.loanForm.credit[0].checked) {credit="Excellent";} else if (document.loanForm.credit[1].checked) {credit="Good";} else {credit="Fair";} if (window.XMLHttpRequest) xmlhttp=new XMLHttpRequest(); else xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); xmlhttp.onreadystatechange = function() { if (xmlhttp.readyState===4){ returnValArray=xmlhttp.responseText.split(","); document.getElementById('rate').value=returnValArray[0]; document.loanForm.payment.value=returnValArray[1]; } } xmlhttp.open('GET', 'compLoanAjax.php?Loan='+ loan + '&Term=' + term + '&Credit=' + credit , true); xmlhttp.send(null); } </script>
HTML form <body> Loan Application Form<br><br> <form name="loanForm"> Enter Loan: <input id='loan' type="text" name="loan" value="" /><br><br> Select Term: <select name="term"> <option value=5>5 years</option> <option value=10>10 years</option> <option value=15>15 years</option> <option value=20>20 years</option> <option value=30>30 years</option> </select><br><br> Select your credit status: <br> <input type="radio" name="credit" value="Excellent" />Excellent<br> <input type="radio" name="credit" value="Good" />Good<br> <input type="radio" name="credit" value="Fair" />Fair<br> <br> Best rate we offer: <input type="text" name="rate" id="rate" /><br><br> Payment: <input type="text" name="payment" id="payment" /><br><br> <input type="button" value="Compute Payment" name="btnCompute" onClick="computeLoan()" /> </form> </body>
PHP file to compute the loan <?php $loan=$_GET['Loan']; $term=$_GET['Term']; $credit=$_GET['Credit']; $rate=.04; if ($loan>500000.00) $rate+=.005; if ($term>20)$rate+=.005; if ($credit=='Excellent') $rate-=.005; if ($credit=='Fair') $rate+=.01; $payment=$loan*$rate/12/(1-pow(1+$rate/12,-12*$term)); echo "$rate,$payment"; ?>
Create a CID listbox and Use AJAX to retrieve Customer Data: Listbox won’t be recreated repetitively
Create a CID listbox and Use AJAX to retrieve Customer Data <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title></title> <script> function showData(CID) { if (window.XMLHttpRequest) xmlhttp=new XMLHttpRequest(); else xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); xmlhttp.onreadystatechange = function() { if (xmlhttp.readyState==4){ window.alert(xmlhttp.responseText); document.getElementById('ResponseDiv').innerHTML = xmlhttp.responseText; returnValArray=xmlhttp.responseText.split(","); document.getElementById('cname').value=returnValArray[0]; document.custDataForm.city.value=returnValArray[1]; document.custDataForm.rating.value=returnValArray[2]; } } xmlhttp.open('GET', 'getCustAJAX.php?CID=' + CID, true); xmlhttp.send(null); } </script> </head>
<body> <form name='custDataForm'> Select CID: <br> <select name = "CID" onchange="showData(this.value)"> <?php $db = new PDO('mysql:host=localhost;dbname=salesdb', 'root', ''); $query="select cid from customers"; $customerIDs = $db->query($query); foreach ($customerIDs as $customerID){ $cid=$customerID["cid"]; echo "<option value= $cid >$cid</option>"; } ?> </select><br><br> <div id='ResponseDiv'> This is a div to hold the response.</div> Name: <input type="text" id="cname" name="cname" value="" /><br><br> City: <input type="text" id =" city" name="city" value="" /><br><br> Rating: <input type="text" id="rating" name="rating" value="" /> </form> </body> Note: This program uses listboxonchange event to pass the selected value, this.value, to procedure.
PHP program to return the data (this is a PHP file, not PHP page) <?php try { $db = new PDO('mysql:host=localhost;dbname=salesdb', 'root', ''); $cid=$_GET['CID']; $query = "SELECT * FROM customers WHERE CID= '$cid'"; $customers = $db->query($query); $customer=$customers->fetch(); $Cname=$customer['cname']; $City=$customer['city']; $Rating=$customer['rating']; $returnVal=$Cname . "," . $City . "," .$Rating; echo $returnVal; } catch (Exception $e) { $error_message = $e->getMessage(); echo "<p>Error message: $error_message </p>"; } ?> Note: This program returns three fields as a string separated by comma so that the JavaScript can use the split function to parse it to an array.
Department/Employees without using AJAX <?php $db = new PDO('mysql:host=localhost;dbname=hrdb', 'root', ''); $query = "SELECT * FROM department;"; $departments=$db->query($query); if (!empty($_GET)) { $did=$_GET['DID']; echo "<form name='deptForm' method='get' action='deptEmployees.php'>"; echo "Select department: <br>"; foreach ($departments as $department) { $deptID=$department['DID']; $dname=$department['DeptName']; $display="$deptID $dname"; if ($deptID==$did) echo "<input type='radio' name='DID' checked value='$deptID' />$display<br>"; else echo "<input type='radio' name='DID' value='$deptID' />$display<br>"; } echo "<br><input type='submit' value='Show Employees' name='btnCompute' />"; echo "</form><br>"; $query = "SELECT * FROM employee WHERE DID= '$did'"; echo "<table border=1><tr><th>EID</th><th>EmpName</th><th>sex</th><th>Salary</th><th>HireDate</th></tr>"; $employees = $db->query($query);
Continue foreach($employees as $employee) { $eid=$employee['EID']; $ename=$employee['Ename']; $sex=$employee['Sex']; $salary=$employee['Salary']; $hiredate=$employee['HireDate']; echo "<tr><td>$eid</td><td>$ename</td><td>$sex</td><td>$salary</td><td>$hiredate</td></tr>"; } } else { echo "<form name='deptForm' method='get' action='deptEmployees.php'>"; echo "Select department: <br>"; foreach ($departments as $department) { $deptID=$department['DID']; $dname=$department['DeptName']; $display="$deptID $dname"; echo "<input type='radio' name='DID' value='$deptID'/> $display<br>"; } echo "<br><input type='submit' value='Show Employees' name='btnCompute' />"; echo "</form>"; } ?>
Department/Employees: AJAX Script <script> function showData() { if (document.getElementById("D1").checked) did="D1"; else if (document.getElementById("D2").checked) did="D2"; else did="D3"; if (window.XMLHttpRequest) xmlhttp=new XMLHttpRequest(); else xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); xmlhttp.onreadystatechange = function() { if (xmlhttp.readyState === 4){ document.getElementById("fromAjax").innerHTML = xmlhttp.responseText; } }; xmlhttp.open('GET', 'getEmpAjax.php?DID=' + did, true); xmlhttp.send(null); } </script>
PHP to create the form with radiobuttons <?php $db = new PDO('mysql:host=localhost;dbname=hrdb', 'root', ''); $query = "SELECT * FROM department;"; echo "<form name='deptForm' >"; echo "Select department: <br>"; $departments=$db->query($query); foreach ($departments as $department) { $deptID=$department['DID']; $dname=$department['DeptName']; $display="$deptID $dname"; echo "<input type='radio' name='DID' id='$deptID' value='$deptID'/> $display<br>"; } echo "<br><input type='button' value='Show Employees' name='btnCompute' onClick='showData()'/>"; echo "</form><br>"; ?> <div id="fromAjax"></div>
PHP File to return employees in table <?php try { $db = new PDO('mysql:host=localhost;dbname=hrdb', 'root', ''); $did=$_GET['DID']; $query = "SELECT * FROM employee WHERE DID= '$did'"; echo "<table border=1><tr><th>EID</th><th>EmpName</th><th>sex</th><th>Salary</th><th>HireDate</th></tr>"; $employees = $db->query($query); foreach($employees as $employee) { $eid=$employee['EID']; $ename=$employee['Ename']; $sex=$employee['Sex']; $salary=$employee['Salary']; $hiredate=$employee['HireDate']; echo "<tr><td>$eid</td><td>$ename</td><td>$sex</td><td>$salary</td><td>$hiredate</td></tr>"; } } catch (Exception $e) { $error_message = $e->getMessage(); echo "<p>Error message: $error_message </p>"; } ?>