Presentation is loading. Please wait.

Presentation is loading. Please wait.

PHP and AJAX ISYS 475. AJAX Asynchronous JavaScript and XML: – JavaScript, Document Object Model, Cascade Style Sheet, XML, server-side script such as.Net,

Similar presentations


Presentation on theme: "PHP and AJAX ISYS 475. AJAX Asynchronous JavaScript and XML: – JavaScript, Document Object Model, Cascade Style Sheet, XML, server-side script such as.Net,"— Presentation transcript:

1 PHP and AJAX ISYS 475

2 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

3

4 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.

5

6 XMLHTTPRequest Javascript 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

7 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"); }

8 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);

9 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 )

10 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.

11 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.

12 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)

13 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.

14 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

15 Example: HTML Page 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); } This is a div to hold the response.

16 Example: PHP Page <?php echo "This is a php response to your request!!!!!!"; ?>

17 JavaScript to compute the future value: No protection of source code

18 Using document.getElementById Enter PV: 4% 5% 6% 7% 8% Select Year: 10 year 15 year 30 year Future Value:

19 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(); }

20 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 " "; echo "Enter present value: "; echo "Select interest rate: "; for ($v=.04; $v<=.08;$v+=.01){ $display=$v*100; if ($v==$myRate) echo " $display% "; else echo " $display% "; } echo " "; echo "Select year: "; for ($v=10; $v<=30;$v+=10){ $display=$v. '-year'; if ($v==$myYear) echo " $display "; else echo " $display "; } $CFV="$". number_format($FV,2); echo "Future value is : "; echo " "; } else { ?> Enter present value: Select interest rate: 4% 5% 6% 7% 8% Select year: 10-year 20-year 30-year Future value is :

21 Using AJAX to compute FV 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); }

22 Enter PV: 4% 5% 6% 7% 8% Select Year: 10 year 15 year 30 year Future Value:

23 The PHP file <?php $pv=$_GET["pv"]; $rate=$_GET["rate"]; $year=$_GET["year"]; $fv=$pv*pow(1+$rate,$year); echo $fv; ?>

24 Loan calculation: Server determines rate based on loan, term, credit passed to PHP by AJAX

25 Passing loan, term, credit to PHP by AJAX 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); }

26 HTML form Loan Application Form Enter Loan: Select Term: 5 years 10 years 15 years 20 years 30 years Select your credit status: Excellent Good Fair Best rate we offer: Payment:

27 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"; ?>

28 Create a CID listbox and Use AJAX to retrieve Customer Data: Listbox won’t be recreated repetitively

29 Create a CID listbox and Use AJAX to retrieve Customer Data 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); }

30 Select CID: <?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 " $cid "; } ?> This is a div to hold the response. Name: City: Rating: Note: This program uses listbox onchange event to pass the selected value, this.value, to procedure.

31 PHP program to return the data ( t his 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 " Error message: $error_message "; } ?> 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.

32 Department/Employees

33 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 " "; echo "Select department: "; foreach ($departments as $department) { $deptID=$department['DID']; $dname=$department['DeptName']; $display="$deptID $dname"; if ($deptID==$did) echo " $display "; else echo " $display "; } echo " "; $query = "SELECT * FROM employee WHERE DID= '$did'"; echo " EID EmpName sex Salary HireDate "; $employees = $db->query($query);

34 Continue foreach($employees as $employee) { $eid=$employee['EID']; $ename=$employee['Ename']; $sex=$employee['Sex']; $salary=$employee['Salary']; $hiredate=$employee['HireDate']; echo " $eid $ename $sex $salary $hiredate "; } } else { echo " "; echo "Select department: "; foreach ($departments as $department) { $deptID=$department['DID']; $dname=$department['DeptName']; $display="$deptID $dname"; echo " $display "; } echo " "; } ?>

35 Department/Employees: AJAX 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); }

36 PHP to create the form with radiobuttons <?php $db = new PDO('mysql:host=localhost;dbname=hrdb', 'root', ''); $query = "SELECT * FROM department;"; echo " "; echo "Select department: "; $departments=$db->query($query); foreach ($departments as $department) { $deptID=$department['DID']; $dname=$department['DeptName']; $display="$deptID $dname"; echo " $display "; } echo " "; ?>

37 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 " EID EmpName sex Salary HireDate "; $employees = $db->query($query); foreach($employees as $employee) { $eid=$employee['EID']; $ename=$employee['Ename']; $sex=$employee['Sex']; $salary=$employee['Salary']; $hiredate=$employee['HireDate']; echo " $eid $ename $sex $salary $hiredate "; } catch (Exception $e) { $error_message = $e->getMessage(); echo " Error message: $error_message "; } ?>


Download ppt "PHP and AJAX ISYS 475. AJAX Asynchronous JavaScript and XML: – JavaScript, Document Object Model, Cascade Style Sheet, XML, server-side script such as.Net,"

Similar presentations


Ads by Google