XHTML, Javascript, AJAX, PHP - Massey University

Transcription

XHTML, Javascript, AJAX, PHP

AJAX Asynchronous JavaScript And XMLAJAX is only a name given to a set of tools that werepreviously existing.AJAX is a technique for creating fast and dynamicweb pages.AJAX allows web pages to be updatedasynchronously by exchanging small amounts ofdata with the server behind the scenes. This meansthat it is possible to update parts of a web page,without reloading the whole page.Classic web pages, (which do not use AJAX) mustreload the entire page if the content should change(this slows down your web page).http://w3schools.com/ajax/ajax intro.asp

AJAX The processing of web page formerly was only in theserver-side, using web services or PHP scripts,before the whole page was sent within the network.Ajax allows to perform processing in the clientcomputer (in JavaScript) with data taken from theserver.“Asynchronous”, means that the response of theserver will be processed only when available; nothaving to wait and to freeze the display of the page.Examples of applications using AJAX: Google Maps (since 2005), Gmail, Youtube, andFacebook tabs.http://www.xul.fr/en-xml-ajax.html

AJAX SERVER? No such thing!Server-side applications just need to serve datausing HTTP Clients using AJAX framework can communicatewith any type of server applications PHP scriptJava servletJSPetc.

Client-Side ProgrammingRecall the technologies comprising DHTML1. HTML (content)2. Document Object Model (DOM) (data structure)3. JavaScript (behaviour)4. Cascading Style Sheets (presentation) JavaScript is a powerful tool for dynamic client-sideprogrammingBut what if we wanted to frequently communicatewith the server?

Recall: Incorporating JavaSciptHandling browsers that do not support Javascript html body script type "text/javascript" !-document.write("Hello World!");//-- /script noscript h2 Your Browser doesn’t support JavaScript! /h2 /noscript /body /html – use HTML comments so that browsers that do not supportJavaScript do not display your code

Client-Server CommunicationJavaScript runs inside a sandbox attached to thebrowserSequence of steps:1. JavaScript code uses DOM to build HTMLdocument.2. GET/POST string is formed.3. Browser encodes HTML and GET/POSTqueries into an HTTP string.4. Browser establishes contact with server andsends the HTTP request.5. Browser receives HTTP response from theserver and displays the body of the page. It would be nice if one could write JavaScript code that candirectly communicate with the server

How does AJAX work? AJAX uses a programming model with display and events. These events are user actions, they call functions associated withelements of the web page. Interactivity is achieved with forms and buttons. DOM allows to link elements of the page with actions and also toextract data from XML or Text files provided by the server.

How does AJAX work?BrowserInternetAn event occurs.Create anXMLHttpRequest questCreate a response andsend data back to thebrowserWait until document has finishedloadingProcess the returned data usingJavascriptUpdate page contentInternet

How does AJAX work?To get data on the server, XMLHttpRequest provides two methods: open: create a connection. send: send a request to the server. Data furnished by the server will be found in the attributes ofthe XMLHttpRequest object: responseXml for an XML file or responseText for a plain text.

XMLHttpRequest objectreadyStateThe value ranges from 0 to 4, 4 means "ready".status200 means OK404 if the page is not found.responseTextholds loaded data as a string of characters.responseXmlholds an XML loaded file, DOM's method allows to extract data.onreadystatechangeproperty that takes a function as value that is invoked when thereadystatechange event is dispatched.These are the properties of an XMLHttpRequestobject that we are going to utilise to retrieve aresponse from the server.http://www.xul.fr/en-xml-ajax.html

Files MySQL database (*.sql) PHP script (*.php) HTML document (*.htm) Javascript (*.js)Communicates with theMySQL server to retrieverecords based on a user’squery

Database Stock ExampleContains the user’s queryPHP scriptoutputAJAX can be used to run PHP scripts that obtain up-to-theminute information stored on a database.The database is queried when the user interacts with theapplication, delivering accurate information without theinconvenience of a page reload.

Database Stock Exampleexample18-2.htm !DOCTYPE html PUBLIC "-//W3C//DTD XHTML dtd" html xmlns "http://www.w3.org/1999/xhtml" xml:lang "en" head title Stock Script /title meta http-equiv "Content-Type" content "text/html;charset ISO-8859-1" / script type "text/javascript" src "getxmlhttprequest.js" /script script type "text/javascript" src "example18-2.js" /script /head .We have two Javascript files in our example. They are loadedin the head section of our HTML file.

Database Stock Exampleexample18-2.htm (continuation ) body h2 Fruit Stock Information: /h2 form action "" method "post" p label for "strStock" Stock Query: /label input type "text" name "strStock" id "strStock"/ /p p input type "button" value "Check" onclick "startJS();"/ /p We have a query input text field and a submit buttonThe submit button includes an onclick event which invokes thestartJS() function when clicked (example18-2.js).

Database Stock Exampleexample18-2.htm (continuation ) body h2 Fruit Stock Information: /h2 form action "" method "post" p label for "strStock" Stock Query: /label input type "text" name "strStock" id "strStock"/ /p p input type "button" value "Check" onclick "startJS();"/ /p div id "strStockResult" /div /form /body /html The div element defines a section used to display the output fromthe PHP script.

AJAX – connect to server, send requestfunction startJS() {example18-2.jsxhrequest null;try {Checks if AJAX is supported.xhrequest getXMLHttpRequest();It checks if the xmlhttprequest}object can be created.catch(error) {document.write("Cannot run Ajax code using this browser");}Obtain query data entered on theformif(xhrequest ! null) {// get form valuesvar strStock document.getElementById("strStock").value;var strUrl "example18-2.php?strStock " strStock;xhrequest.onreadystatechange changePage;xhrequest.open("GET", strUrl, true);xhrequest.send(null);}}.Null because we have appended thequery parameters alreadyPHP script file User’s querySets a function that obtainsthe data output from PHPscriptOpen a connection to the PHPscript, then pass the datastartJS() is invoked when the button is clicked.

AJAX – obtain output from serverexample18-2.js (continuation )Check if data is availablefunction changePage() {if (xhrequest.readyState 4 && xhrequest.status 200) {var strResponse rStockResult").innerHTML strResponse;}}Retrieve response from the serverchangePage() obtains the data output from the PHP scriptthen stores it into a variable named strResponse.The data is then injected into the strStockResult div section defined in the HTML. This is accomplished using theinnerHTML method.

XMLHttpRequest object an object used both for making the XMLHttpRequest andretrieving the server’s response We have to wait for the data to be available to process it. In this purpose, the state of availability of data isgiven by the readyState attribute of XMLHttpRequest.States of readyState 0: not initialized.1: connection established.2: request received.3: answer in process.4: finished.only the last one is really useful!

getXMLHttpRequest() – user-definedgetxmlhttprequest.jsfunction getXMLHttpRequest() {var xhrequest null;The window object represents anopen window in a browser.Check if this property is presentif(window.XMLHttpRequest) {// If IE7, Mozilla, Safari, etc: Use native objecttry {xhrequest new XMLHttpRequest();return xhrequest;Use native scripting}catch(exception) {// OK, just carry on looking}Continued.}Our Javascript needs to be able to acquire the appropriate type of XMLHttpRequest object,depending on the browser the script is running in.

getXMLHttpRequest() – user-definedgetxmlhttprequest.jsTesting is done starting from themost recent backwards.else {// .otherwise, use the ActiveX control for IE5.x and IE6var IEControls .XMLHttp.3.0","MSXML2.XMLHttp"];for(var i 0; i IEControls.length; i ) {try {xhrequest new ActiveXObject(IEControls[i]);return xhrequest;}catch(exception) {// OK, just carry on looking}Microsoft has developed differentimplementations of theXMLHttpRequest object over time.ActiveXObject is an older versionimplementation.}// if we got here we didn’t find any matchesthrow new Error("Cannot create an XMLHttpRequest");}}

PHP Script ?php strStock GET["strStock"];example18-2.php dbLocalhost mysql connect("localhost", "root", "") or die("Could not connect: " . mysql error());mysql select db("stock", dbLocalhost ) or die("Could not find database: " . mysql error()); dbRecords mysql query("SELECT * FROM stock WHERE Name ' strStock' ", dbLocalhost ) or die("Problem reading table: " . mysql error()); intRecords mysql num rows( dbRecords );Contains the user’s queryif ( intRecords 0)echo " p Stock Item ' strStock' Unknown. /p ";Table named stockelse {while ( arrRecords mysql fetch array( dbRecords)) { strDescription arrRecords ["Description"]; intQuantity arrRecords["Quantity"];echo " p strDescription: Currently we have intQuantity of boxes. /p ";}}? Queries the database and outputs the corresponding records found

Stock Table (Structure)Id is a primary key, also set to auto increment.You need to create your database first using phpMyAdmin,then import the stock.sql file containing the structure and dataentries.

Stock Table (data) You can populate the database easily using phpMyAdmin. You can import the stock.sql file containing the structure andinitial data entries. You can select the INSERT tag to add more data entries.

Files Images (*.jpg) PHP script (*.php) HTML document (*.htm) Javascript (*.js)

Zooming photo thumbnail application user is presented with a series of small thumbnails ofphotos Upon moving a mouse over one of the thumbnails, alarger image is displayed.

Zooming photo thumbnail application Using standard Javascript and (X)HTML would require all of the images to bedownloaded whenever a user moves a mouse over an image. Using AJAX, only the images that the user wishes to zoom in on aredownloaded and a full page refresh is avoided.

CSS float: applied on an Image html head style type "text/css" img{float:right;} /style /head Image float.htmCSS-style definitionImage file body p In the paragraph below, we have added an image with style b float:right /b . Theresult is that the image will float to the right in the paragraph. /p p img src "logocss.gif" width "95" height "84" / This is some text. This is some text. This is some text.This is some text. This is some text. This is some text.This is some text. This is some text. This is some text.This is some text. This is some text. This is some text. /p /body Elements are floated horizontally, this means that an /html element can only be floated left or right, not up or down.

CSS float: applied on an Image

html script type "text/javascript" src "getxmlhttprequest.js" /script script type "text/javascript" src "example18-3.js" /script Example18-3.htm style type "text/css" CSS-style definition#big {float: left;}Image file#small {float: left;width: 320px;} /style /head Embedded CSS-style definition is included to define theStyle of the small thumbnail photos and the largerzoomed image.

html h2 Zooming Pictures: /h2 Example18-3.htm (continuation ) div id "small" img src "graphics/1s.jpg" onmouseover "startJS(1);" alt "small picture"/ img src "graphics/2s.jpg" onmouseover "startJS(2);" alt "small picture"/ img src "graphics/3s.jpg" onmouseover "startJS(3);" alt "small picture"/ img src "graphics/4s.jpg" onmouseover "startJS(4);" alt "small picture"/ img src "graphics/5s.jpg" onmouseover "startJS(5);" alt "small picture"/ img src "graphics/6s.jpg" onmouseover "startJS(6);" alt "small picture"/ img src "graphics/7s.jpg" onmouseover "startJS(7);" alt "small picture"/ img src "graphics/8s.jpg" onmouseover "startJS(8);" alt "small picture"/ img src "graphics/9s.jpg" onmouseover "startJS(9);" alt "small picture"/ img src "graphics/10s.jpg" onmouseover "startJS(10);" alt "small picture"/ img src "graphics/11s.jpg" onmouseover "startJS(11);" alt "small picture"/ img src "graphics/12s.jpg" onmouseover "startJS(12);" alt "small picture"/ /div div id "big" img src "graphics/1l.jpg" width '600' alt "large picture"/ /div /body The alt attribute provides alternative /html Large imageinformation for an image if a user forsome reason cannot view it Each of the thumbnail images is displayed within a division with an id “small”.

AJAX – connect to server, send requestfunction startJS(intPicture) {example18-2.jsxhrequest null;try {Contains a number representing thexhrequest getXMLHttpRequest();image the mouse has moved over.}catch(error) {document.write("Cannot run Ajax code using this browser");}Checks if AJAX is supported.if(xhrequest ! null) {// get form valuesIt checks if the xmlhttprequestobject can be created.var strUrl "example18-3.php?intPicture "xhrequest.onreadystatechange changePage;xhrequest.open("GET", strUrl, true);xhrequest.send(null);}}.Null because we have appended thequery parameters already intPicture;PHP script file User’s querySets a function that obtainsthe data output from PHPscriptOpen a connection to the PHPscript, then pass the datastartJS() is invoked when the button is clicked.

AJAX – obtain output from serverexample18-3.js (continuation )Check if data is availablefunction changePage() {if (xhrequest.readyState 4 && xhrequest.status 200) {var strResponse big").innerHTML strResponse;}}Retrieve response from the serverchangePage() obtains the data output from the PHP scriptthen stores it into a variable named strResponse.The data is then injected into the strStockResult div section defined in the HTML. This is accomplished using theinnerHTML method.

PHP Script ?phpexample18-3.php intPicture GET["intPicture"];echo " img src 'graphics/ intPicture" . "l.jpg' width '600' / ";? Name retrieved viaGETAppend an Extension to thefile name the PHP script obtains the value of the image the mouse has movedover, passed via the GET method and stores it in a variable called intPicture. It then outputs the (X)HTML element pointing to the correspondinglarge image.

Files Images (*.jpg) MySQL (*.sql) PHP script (*.php) HTML document (*.htm) Javascript (*.js)

Consider developing a website that displays a graphshowing in almost real-time some data about yourcustomers, sales, etc.Using AJAX, we can minimise the effect of thatcontinuously updating graph on the users of your website.

html !DOCTYPE html PUBLIC "-//W3C//DTD XHTML dtd" html xmlns "http://www.w3.org/1999/xhtml" xml:lang "en" Example18-4.htm head title Graph Script /title meta http-equiv "Content-Type" content "text/html; charset ISO-8859-1" / script type "text/javascript" src "getxmlhttprequest.js" /script script type "text/javascript" src "example18-4.js" /script style type "text/css" CSS-style definition#graphBars {float: left;}Defines a CSS-style for an Image filethat will display the scale of the chart#graphScale {float: left;width: 40px;} Embedded CSS-style definition is included /style /head define the Style of the graphing areato

htmlExample18-4.htm (continuation ) body onload "startJS();" h2 Graph: /h2 div id "graph" /div when the web page is loaded, anonload event invokes the startJS()functiona div section that defines thegraphing area /body /html The div section will be populatedprogrammatically via a combination of php scriptand AJAX.

AJAX – connect to server, send requestfunction startJS( ) {xhrequest null;try {xhrequest getXMLHttpRequest();}catch(error) {document.write("Cannot run Ajax!");}if(xhrequest ! null) {// get form valuesvar objDate new Date();var intSecs objDate.getTime();}.example18-4.jsChecks if AJAX is supported.It checks if the xmlhttprequestobject can be created.A Data object is created and used toreturn the number of secondselapsed since 1/1/1970 using thegetTime() functionvar strUrl "example18-4.php?intSecs " intSecs;xhrequest.onreadystatechange changePage;xhrequest.open("GET", strUrl, true);xhrequest.send(null);setTimeout("startJS()", 500);} }Call startJS() function (itself!) after500 millisecondsWe want to force thebrowser to obtain new datavia the PHP scriptSets a function that obtainsthe data output from PHPscriptOpen a connection to the PHPscript, then pass the datastartJS() is invoked when the button is clicked.

AJAX – obtain output from serverexample18-4.js (continuation )Check if data is availablefunction changePage() {if (xhrequest.readyState 4 && xhrequest.status 200) {var strResponse graph").innerHTML strResponse;}}Retrieve response from the serverchangePage() obtains the data output from the PHP scriptthen stores it into a variable named strResponse.The data is then injected into the graph div section definedin the HTML. This is accomplished using the innerHTMLmethod.

PHP Scriptexample18-4.php ?php dbLocalhost mysql connect("localhost", "root", "") or die("Could not connect: " . mysql error());mysql select db(“graph", dbLocalhost ) or die("Could not find database: " . mysql error());srand((double) microtime() * 1000000); intPercentage rand(0,99);Generate a random numberbetween [0, 99] dbWriteRecords mysql query("INSERT INTO percentageValues VALUES ('',' intPercentage')", dbLocalhost) or die("Problem reading table: " . mysql error()); dbRecords mysql query("SELECT * FROM percentageValues", dbLocalhost )or die("Problem reading table: " . mysql error());Table named intCount mysql num rows( dbRecords );percentageValuesif ( intCount 20) {Last 20 entries intStart intCount - 20; dbRecords mysql query(" SELECT * FROM percentageValues LIMIT intStart, 20", dbLocalhost) or die("Problem reading table: " . mysql error());}.Continued. the PHP script queries (INSERT & SELECT) thedatabase and outputs the corresponding recordsfound.

PHP Script arrPercent array 8-4.php intSize count( arrPercent);(continuation ) intCount 0;while ( arrRecords mysql fetch array( dbRecords)) { arrPercent[ intCount ] arrRecords["Percentage"];Fetch the records}graph( arrPercent, intSize);A field in the tablefunction graph( arrData, intSize) { intBarWidth 10;// intBarSpacing 10; intMultiplier 1.5; intSize count( arrData);echo " div id 'graphScale' img src 'graphics/scale.gif' width '27' height '150' / /div ";echo " div id 'graphBars' ";echo " img src 'graphics/hiddenbar.gif' width '0' height '" . 99 * intMultiplier . "' ";for( intCount 0; intCount intSize; intCount ) {echo " img src 'graphics/redbar.gif' width ' intBarWidth' height '" . arrData[ intCount]* intMultiplier . "' ";Generate a graph by displaying an}image repetitivelyecho " /div ";}? the graph function uses 2 div sections to define the scaleand the graphing area.

jquery jQuery is a library of JavaScript Functions. jQuery is a lightweight "write less, do more" JavaScript library. The jQuery library contains the following features: HTML element selectionsHTML element manipulationCSS manipulationHTML event functionsJavaScript Effects and animationsHTML DOM traversal and ry/jquery intro.asp

jquery The jQuery library is stored in a single JavaScript file, containing all thejQuery functions.It can be added to a web page with the following mark-up: head script type "text/javascript" src "jquery.js" /script /head Jquery libraryNote: the script tag should be inside the page's head section.http://w3schools.com/jquery/jquery intro.asp

Jquery libraryIf you don't want to store the jQuery library on your owncomputer, you can use the hosted jQuery library fromGoogle or Microsoft. head script type "text/javascript"src /jquery.min.js" /script /head head script type "text/javascript"Jquery librarysrc 2.min.js" /script /head Note: the script tag should be inside the page's head section.http://w3schools.com/jquery/jquery intro.asp

jQuery uses CSS selectors to select HTML elements.

Recall: 1. Incorporating CSSExample: External style sheetmystyle.csshr {color:sienna;}p {margin-left:20px;}body .htm head link rel "stylesheet" type "text/css" href "mystyle.css” /head

Recall: 1. Applying CSS to an HTMLelement You can apply CSS-style formatting to an HTML element either by using anID selector or a Class selector.ID SELECTOR The id selector is used to specify a style for a single, unique element. The id selector uses the id attribute of the HTML element, and is defined with a "#". The style rule below will be applied to the element with id "para1": Do NOT start an ID name with a number! It will not work in Mozilla/Firefox.General Syntax:#ID-name{Property:value;Property:value;/*. and so on. */}ID selector application: h1 id ”ID-name” Internet programming /h1

Recall: 2a. Applying CSS to an HTMLelement You can apply CSS-style formatting to an HTML element either by using an IDselector or a Class selector.class SELECTOR The class selector is used to specify a style for a group of elements. Unlike the idselector, the class selector is most often used on several elements. This allows you to set a particular style for any HTML elements with the same class. The class selector uses the HTML class attribute, and is defined with a "."General *. and so on. */}class selector application: h1 class ”class-name” Internet programming /h1 p class ”class-name” Dynamic HTML: CSS, HTML, DOM, Javascript /p

Recall: 2b. Applying CSS to an HTMLelement You can apply CSS-style formatting to an HTML element either by using an ID selector or a Classselector.class SELECTOR You can also specify that only specific HTML elements should be affected by aclass.General Syntax:/* this class selector is only applicable to alue;/*. and so on. */}class selector application: p class ”class-name” Dynamic HTML: CSS, HTML, DOM, Javascript /p

jquery The jQuery library is stored a single JavaScript file, containing all thejQuery functions. (this).hide()Demonstrates the jQuery hide() function, hiding the current HTML element. ("#test").hide()Demonstrates the jQuery hide() function, hiding the element with id "test". ("p").hide()Demonstrates the jQuery hide() function, hiding all p elements. (".test").hide()Demonstrates the jQuery hide() function, hiding all elements withclass "test".http://w3schools.com/jquery/jquery syntax.asp

Document Ready Function to prevent any jQuery code from running beforethe document is finished loading (is it ready?) (document).ready(function(){// jQuery functions go here.});

jquery html head jquery1.htm script type "text/javascript" src "jquery-1.4.2.min.js" /script script type "text/javascript" (document).ready( function() {Jquery library ("button").click( function() { ("div").load('test1.txt');On click event, load the} );contents from test1.txt into the} );div section /script /head Modify the body contents of the div h2 Let AJAX change this text /h2 /div button Change Content /button /body /html http://docs.jquery.com/Downloading jQuery#Current Release div section

jquery The jQuery library is stored as a single JavaScript file, containing all thejQuery functions.The jQuery syntax is tailor made for selecting HTML elementsand perform some action on the element(s).Basic syntax is: (selector).action() (dollar sign) to define jQuery(selector) to "query (or find)" HTML elementsjQuery action() to be performed on the element(s)http://w3schools.com/jquery/jquery syntax.asp

jqueryJquery2-slide.htm html head script type "text/javascript" src "jquery-1.4.2.min.js" /script script type "text/javascript" (document).ready(function(){ (".flip").click(function(){Jquery library (".panel").slideToggle("slow");});}); /script On click event, (toggle) slide style type "text/css" up or slide-down the htmldiv.panel,p.flipelement of class panel{margin:0px;padding:5px;Settings for bothtext-align:center;the panel andbackground:#e5eecc;flip classesborder:solid 1px #c3c3c3;}div.panel{height:120px;display:none;Do not show the}panel initially /style /head

jqueryJquery2-slide.htm body div class "panel" p Special effects like this could be easily incorporated. /p p into your website using jquery! :) /p /div div section ofclass panel p class "flip" Show/Hide Panel /p /body /html Serves as a titlebar

jquery It is recommended that you put your jQueryfunctions in a separate .js file

ReferencesDynamic Web Application Development usingPHP and MySQL – by Stobart and Parsonshttp://w3schools.com/ajax/ajax www.jquery.comhttp://w3schools.com/jquery

AJAX Asynchronous JavaScript And XML AJAX is only a name given to a set of tools that were previously existing. AJAX is a technique for creating fast and dynamic web pages. AJAX allows web pages to be updated asynchronously by exchanging small amounts of data with the server behind the scenes.This means that it is possible to update parts of a web page,