Sie sind auf Seite 1von 14

WHAT & HOW

yewkh©2007 Slide 1
Learning Outcomes

At the end of this topic, students should be able to:


1. What is AJAX?
2. Why use AJAX?
3. How to use AJAX in JSP?
4. How to use AJAX in PHP and connecting to MySQL?

yewkh©2007 Slide 2
Step-by-step

1. AJAX is a Web 2.0 technology, Asynchronous JavaScript And XML. Used by


Gmail.

2. It uses javascript to call function xmlHttpRequest();

3. We use AJAX code to print a diffrent page in "div" every 5 seconds.

4. Why? Becuase we sometimes have have an ever changing data in certain


section of html/php file.

5. How?
•Put function whose code is using everchanging data in "div"
•Then, add onLoad="myFunction()" in the body tag.

yewkh©2007 Slide 3
Example
function ajaxFunction(){
var xmlHttp;

try{xmlHttp=new XMLHttpRequest();}
catch (e){
try{xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");}
catch (e){
try{xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");}
catch (e){
alert("Your browser does not support AJAX!");
return false;
}
}
}

xmlHttp.onreadystatechange =function()
{if(xmlHttp.readyState==4)
{document.getElementById('stable').innerHTML=xmlHttp.responseText;}
}

xmlHttp.open("POST","ajax2.php",true);

xmlHttp.send(null);
}

yewkh©2007 Slide 4
Example
function myFunction(){
ajaxFunction();
var t=setTimeout("smarm()",5000);
http.setRequestHeader("If-Modified-Since", "Fri, 1 Jan 2010 00:00:00 GMT");
}

yewkh©2007 Slide 5
Using AJAX in JSP: Step-by-step

1. Ajax is simple JavaScript script which work with XML Http request. It can be
implemented in JSP, struts and servlet projects.

2. Ajax allows loading page in background without refreshing and submitting full
page.

3. How to use Ajax in JSP


a. Get Ajax framework for java
b. Use simple Ajax script for JSP

4. Frameworks for Ajax in java are available from many third party websites. This
Ajax framework comes in taglib and tags can use in front end page JSP.
• https://ajax.dev.java.net/
• http://ajaxtags.sourceforge.net/
• http://ajaxanywhere.sourceforge.net/

yewkh©2007 Slide 6
AJAX scripts for JSP
1. There are plenty of scripts available for auto complete, load page, validation,
and menu navigation in Ajax which can be used in JSP.

2. The following example use the following files:


• index.jsp
• ajaxjs.js Index.jsp ajaxjs.js loadJSP.jsp
• loadJSP.jsp

index.jsp
<html>
<head>
<script src="ajaxjs.js"></script>
</head>
<body>
<a href="javascript:loadContent('parameterValue')">Load Ajax content</a>
<div id="prtCnt"></div>
</body>
</html>

yewkh©2007 Slide 7
AJAX scripts for JSP
1. Script to get XmlHttp object.

ajaxjs.js function getOutput()


var xmlhttp {
if (xmlhttp.readyState==4) {
function loadContent(str) document.getElementById("prtCnt").innerHTML
{ =xmlhttp.responseText;}
xmlhttp=GetXmlHttpObject(); }
if (xmlhttp==null)
{ function GetXmlHttpObject()
alert (“Browser does not support Ajax HTTP"); {
return; if (window.XMLHttpRequest){return new XMLHttpRequest();}
} if (window.ActiveXObject)
var url="loadJSP.jsp"; {return new ActiveXObject("Microsoft.XMLHTTP");}
url=url+"?q="+str; return null;
xmlhttp.onreadystatechange=getOutput; }
xmlhttp.open("GET",url,true);
xmlhttp.send(null);
}

yewkh©2007 Slide 8
AJAX scripts for JSP
1. JSP file which loads in the background.

loadJSP.jsp
<%@ page contentType="text/html; charset=iso-8859-1" language="java" %>
<%
String q =request.getParameter("q");
String str="This is JSP string loading from JSP page in ajax, loading time :";
java.util.Date dt=new java.util.Date();
out.print(str+dt);
%>

yewkh©2007 Slide 9
Using AJAX with PHP and MySQL
1. PHP can use AJAX for INTERACTIVE communication with MySQL database.

id FirstName LastName Age Hometown Job


1 Peter Pan 31 Newark Carpenter
2 Lois Griffin 30 Newport Piano Teacher
3 Joseph Carrera 29 Buffalo Mechanic
4 Glenn John 31 Syracuse Pilot

yewkh©2007 Slide 10
Using AJAX with PHP and MySQL
HTML + Javascript: When a user selects from the dropdown, a function called "showUser()"
is executed. The function is triggered by the "onchange" event:
<html> <body>
<head> <form>
<script type="text/javascript"> <select name="users" onchange="showUser(this.value)">
function showUser(str) <option value="">Select a person:</option>
{ <option value="1">Peter Pan</option>
if (str=="") <option value="2">Lois Griffin</option>
{ <option value="3">Glenn Quagmire</option>
document.getElementById("txtHint").innerHTML=""; <option value="4">Joseph Carrera</option>
return; </select>
} </form>
if (window.XMLHttpRequest) <br />
{// code for IE7+, Firefox, Chrome, Opera, Safari <div id="txtHint"><b>Person info will be listed here.</b></div>
xmlhttp=new XMLHttpRequest();
} </body>
else </html>
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
The showUser() function does the following:
if (xmlhttp.readyState==4 && xmlhttp.status==200) 1. Check if a person is selected
{
document.getElementById("txtHint").innerHTML=xmlhttp.responseText;
2. Create an XMLHttpRequest object
} 3. Create the function to be executed when the
}
xmlhttp.open("GET","getuser.php?q="+str,true); server response is ready
xmlhttp.send(); 4. Send the request off to a file on the server.
}
</script> Notice that a parameter (q) is added to the
</head> URL (with the content of the dropdown list)

yewkh©2007 Slide 11
Using AJAX with PHP and MySQL
PHP: The page on the server called by the JavaScript above is a PHP file called "getuser.php".
The source code in "getuser.php" runs a query against a MySQL database, and returns the
result in an HTML table:
<?php echo "<table border='1'>
$q=$_GET["q"]; <tr>
<th>Firstname</th>
$con = mysql_connect('localhost', 'peter', 'abc123'); <th>Lastname</th>
if (!$con) <th>Age</th>
{ <th>Hometown</th>
die('Could not connect: ' . mysql_error()); <th>Job</th>
} </tr>";

mysql_select_db("ajax_demo", $con); while($row = mysql_fetch_array($result))


{
$sql="SELECT * FROM user WHERE id = '".$q."'"; echo "<tr>";
echo "<td>" . $row['FirstName'] . "</td>";
$result = mysql_query($sql); echo "<td>" . $row['LastName'] . "</td>";
echo "<td>" . $row['Age'] . "</td>";
echo "<td>" . $row['Hometown'] . "</td>";
echo "<td>" . $row['Job'] . "</td>";
The query is sent from the JavaScript to the PHP echo "</tr>";
file. }
PHP opens a connection to a MySQL server echo "</table>";
The correct person is found mysql_close($con);
An HTML table is created, filled with data, and ?>
sent back to the "txtHint" placeholder

yewkh©2007 Slide 12
Summary

An active page, i.e. the display page contains script that calls a
special AJAX function (in a javascript file). The AJAX function
will call (in periodical manner) another inset page. The inset page
has components that change regularly, e.g. from real-time
database.

At the server side, a PHP file may be needed to communicate


with the database, e.g. MySQL. The PHP file will send back the
requested data to update the presentation of the inset page.

The inset page will be periodically used by the AJAX function to


update the section of the display page.

yewkh©2007 Slide 13
Q&A

yewkh©2007 Slide 14

Das könnte Ihnen auch gefallen