+ All Categories
Home > Documents > XHTML, Javascript, AJAX, PHP - Informatika...

XHTML, Javascript, AJAX, PHP - Informatika...

Date post: 29-Jun-2020
Category:
Upload: others
View: 2 times
Download: 0 times
Share this document with a friend
76
XHTML, XHTML, Javasc Javasc cript cript, AJAX, PHP , AJAX, PHP
Transcript
Page 1: XHTML, Javascript, AJAX, PHP - Informatika Unsyiahinformatika.unsyiah.ac.id/~viska/pbw/07-AJAX-PHP.pdf · •These events are user actions, they call elements of the web page. •Interactivityis

XHTML, XHTML, JavascriptJavascriptJavascriptJavascript, AJAX, PHP, AJAX, PHP

Page 2: XHTML, Javascript, AJAX, PHP - Informatika Unsyiahinformatika.unsyiah.ac.id/~viska/pbw/07-AJAX-PHP.pdf · •These events are user actions, they call elements of the web page. •Interactivityis
Page 3: XHTML, Javascript, AJAX, PHP - Informatika Unsyiahinformatika.unsyiah.ac.id/~viska/pbw/07-AJAX-PHP.pdf · •These events are user actions, they call elements of the web page. •Interactivityis

AJAXAJAX

AAsynchronous JJavaScript

AJAX is only a name given to a set of tools that were previously existing.

AJAX is a technique for creating web pages.

AJAX allows web pages to be AJAX allows web pages to be asynchronouslyasynchronously by exchanging small amounts of data with the server behind the scenesthat it is possible to update parts of a web page, withoutwithout reloading the whole pagereloading the whole page

Classic web pages, (which do not use AJAX) must reload the entire page if the content should change (this slows down your web page).

AJAXAJAX

avaScript AAnd XXML

is only a name given to a set of tools that were

is a technique for creating fastfast and dynamicdynamic

allows web pages to be updatedupdatedallows web pages to be updatedupdatedby exchanging small amounts of

behind the scenes. This means that it is possible to update parts of a web page,

reloading the whole pagereloading the whole page.

Classic web pages, (which do not use AJAX) must reload the entire page if the content should change (this slows down your web page).

http://w3schools.com/ajax/ajax_intro.asp

Page 4: XHTML, Javascript, AJAX, PHP - Informatika Unsyiahinformatika.unsyiah.ac.id/~viska/pbw/07-AJAX-PHP.pdf · •These events are user actions, they call elements of the web page. •Interactivityis

AJAXAJAX

The processing of web page formerly was only in the server-side, using web services or PHP scripts, before the whole page was sent within the network.

Ajax allows to perform processing in the client computer (in JavaScriptJavaScript) with data taken from the server.server.

“AsynchronousAsynchronous”, means that the response of the server will be processed only when available; not having to wait and to freeze the display of the page.

Examples of applications using AJAX: Google Maps (since 2005), Gmail, Youtube, and

Facebook tabs.

AJAXAJAX

The processing of web page formerly was only in the side, using web services or PHP scripts,

before the whole page was sent within the network.

Ajax allows to perform processing in the client ) with data taken from the

”, means that the response of the server will be processed only when available; not having to wait and to freeze the display of the page.

Examples of applications using AJAX:Google Maps (since 2005), Gmail, Youtube, and

http://www.xul.fr/en-xml-ajax.html

Page 5: XHTML, Javascript, AJAX, PHP - Informatika Unsyiahinformatika.unsyiah.ac.id/~viska/pbw/07-AJAX-PHP.pdf · •These events are user actions, they call elements of the web page. •Interactivityis

AJAX SERVER??AJAX SERVER??

No such thing!No such thing!

Server-side applications just need to serve data

using HTTPHTTP

Clients using AJAXAJAX framework can communicate Clients using AJAXAJAX framework can communicate

with any type of server applications PHP script

Java servlet

JSP

etc.

AJAX SERVER??AJAX SERVER??

side applications just need to serve data

framework can communicateframework can communicate

with any type of server applications

Page 6: XHTML, Javascript, AJAX, PHP - Informatika Unsyiahinformatika.unsyiah.ac.id/~viska/pbw/07-AJAX-PHP.pdf · •These events are user actions, they call elements of the web page. •Interactivityis
Page 7: XHTML, Javascript, AJAX, PHP - Informatika Unsyiahinformatika.unsyiah.ac.id/~viska/pbw/07-AJAX-PHP.pdf · •These events are user actions, they call elements of the web page. •Interactivityis

ClientClient--Side ProgrammingSide Programming

Recall the technologies comprising

1. HTML (contentcontent)

2. Document Object Model (DOM) (

3. JavaScript (behaviourbehaviour

4. Cascading Style Sheets (

JavaScriptJavaScript is a powerful tool for dynamic clientprogramming

But what if we wanted to frequently communicate with the server?

Side ProgrammingSide Programming

Recall the technologies comprising DHTMLDHTML

Document Object Model (DOM) (data structuredata structure)

behaviourbehaviour)

Cascading Style Sheets (presentationpresentation)

is a powerful tool for dynamic client-side

But what if we wanted to frequently communicate

Page 8: XHTML, Javascript, AJAX, PHP - Informatika Unsyiahinformatika.unsyiah.ac.id/~viska/pbw/07-AJAX-PHP.pdf · •These events are user actions, they call elements of the web page. •Interactivityis

Recall: Recall: Incorporating Incorporating

<html><body><script type="text/javascript">

<!--document.write("Hello World!");

//--></script>

Handling browsers that do not support Javascript

</script>

<noscript><h2>Your Browser doesn’t support JavaScript! </h2>

</noscript></body></html>

– use HTML comments so that browsers that do not support JavaScript do not display your code

Incorporating Incorporating JavaSciptJavaScipt

Handling browsers that do not support Javascript

<h2>Your Browser doesn’t support JavaScript! </h2>

so that browsers that do not support JavaScript do not display your code

Page 9: XHTML, Javascript, AJAX, PHP - Informatika Unsyiahinformatika.unsyiah.ac.id/~viska/pbw/07-AJAX-PHP.pdf · •These events are user actions, they call elements of the web page. •Interactivityis
Page 10: XHTML, Javascript, AJAX, PHP - Informatika Unsyiahinformatika.unsyiah.ac.id/~viska/pbw/07-AJAX-PHP.pdf · •These events are user actions, they call elements of the web page. •Interactivityis

ClientClient--Server CommunicationServer Communication

JavaScriptJavaScript runs inside a sandbox attached to the browser

Sequence of steps:

1.1. JavaScriptJavaScript code uses DOM to build document.

2. GET/POST string is formed.2. GET/POST string is formed.

3. Browser encodes HTMLqueries into an HTTPHTTP string.

4. Browser establishes contact with server and sends the HTTPHTTP request.

5. Browser receives HTTPHTTPserver and displays the body of the page.

It would be nice if one could write JavaScript code that can directly communicate with the

Server CommunicationServer Communication

runs inside a sandbox attached to the

code uses DOM to build HTML

string is formed.string is formed.

HTML and GET/POSTstring.

establishes contact with server and request.

HTTPHTTP response from the server and displays the body of the page.

It would be nice if one could write JavaScript code that can with the server

Page 11: XHTML, Javascript, AJAX, PHP - Informatika Unsyiahinformatika.unsyiah.ac.id/~viska/pbw/07-AJAX-PHP.pdf · •These events are user actions, they call elements of the web page. •Interactivityis

• AJAXAJAX uses a programming model with

• These events are user actionsuser actions, they call elements of the web page.

• InteractivityInteractivity is achieved with formsforms

• DOMDOM allows to link elements of the page with

How does How does AJAXAJAX

• DOMDOM allows to link elements of the page with extract data from XMLXML or Text or Text files provided by the server.

uses a programming model with displaydisplay and eventsevents.

, they call functionsfunctions associated with

formsforms and buttonsbuttons.

allows to link elements of the page with actionsactions and also to

AJAXAJAX work?work?

allows to link elements of the page with actionsactions and also to files provided by the server.

Page 12: XHTML, Javascript, AJAX, PHP - Informatika Unsyiahinformatika.unsyiah.ac.id/~viska/pbw/07-AJAX-PHP.pdf · •These events are user actions, they call elements of the web page. •Interactivityis

How does How does AJAXAJAX

BrowserBrowser

An event occurs...

Create an XMLHttpRequest object

SendXMLHttpRequest

BrowserBrowser

Wait until document has finished loading

Process the returned data using Javascript

Update page content

AJAXAJAX work?work?

ServerServer

Internet

ProcessHttpRequestHttpRequest

Create a response and send data back to the browser

Internet

Page 13: XHTML, Javascript, AJAX, PHP - Informatika Unsyiahinformatika.unsyiah.ac.id/~viska/pbw/07-AJAX-PHP.pdf · •These events are user actions, they call elements of the web page. •Interactivityis

To get data on the serverTo get data on the server, XMLHttpRequestXMLHttpRequest

• openopen: create a connection.• sendsend: send a request to the server.

•• Data furnished by the server Data furnished by the server the XMLHttpRequestXMLHttpRequest objectobject:

How does How does AJAXAJAX

• responseXml for an XMLXML• responseText for a plain textplain text

XMLHttpRequestXMLHttpRequest provides two methods:

: send a request to the server.

Data furnished by the server Data furnished by the server will be found in the attributes of :

AJAXAJAX work?work?

XMLXML file orplain textplain text.

Page 14: XHTML, Javascript, AJAX, PHP - Informatika Unsyiahinformatika.unsyiah.ac.id/~viska/pbw/07-AJAX-PHP.pdf · •These events are user actions, they call elements of the web page. •Interactivityis

readyState The value ranges from 0 to 4,

status200 means OK404 if the page is not found.

responseText holds loaded data as a string of characters.

responseXml holds an XML loaded file, DOM's method allows to extract data.

XMLHttpRequestXMLHttpRequest

onreadystatechangeproperty that takes a functionreadystatechange event

These are the propertiesproperties of an objectobject that we are going to utilise to retrieve a response from the server.

0 to 4, 4 means "ready".

if the page is not found.

holds loaded data as a string of characters.

holds an XML loaded file, DOM's method allows to extract data.

XMLHttpRequestXMLHttpRequest objectobject

function as value that is invoked when the event is dispatched.

http://www.xul.fr/en-xml-ajax.html

of an XMLHttpRequest XMLHttpRequest that we are going to utilise to retrieve a

Page 15: XHTML, Javascript, AJAX, PHP - Informatika Unsyiahinformatika.unsyiah.ac.id/~viska/pbw/07-AJAX-PHP.pdf · •These events are user actions, they call elements of the web page. •Interactivityis

•• MySQLMySQL database database

Files

•• MySQLMySQL database database

•• PHP script PHP script ((*.php*.php

•• HTML document HTML document

•• JavascriptJavascript ((*.js*.js

database database ((*.sql*.sql))database database ((*.sql*.sql))

*.php*.php))

HTML document HTML document ((*.htm*.htm))

*.js*.js))Communicates with the

MySQL server to retrieve records based on a user’s

query

Page 16: XHTML, Javascript, AJAX, PHP - Informatika Unsyiahinformatika.unsyiah.ac.id/~viska/pbw/07-AJAX-PHP.pdf · •These events are user actions, they call elements of the web page. •Interactivityis

DatabaseDatabase Stock ExampleStock Example

The database is queriedqueried when the application, delivering accurate information without the inconvenience of a page reload.

AJAXAJAX can be used to runrun PHP scriptsminute information stored on a database.

Stock ExampleStock Example

Contains the user’s query

when the user interacts user interacts with the application, delivering accurate information without the inconvenience of a page reload.

PHP scripts that obtain up-to-the-minute information stored on a database.

PHP scriptPHP scriptoutputoutput

Page 17: XHTML, Javascript, AJAX, PHP - Informatika Unsyiahinformatika.unsyiah.ac.id/~viska/pbw/07-AJAX-PHP.pdf · •These events are user actions, they call elements of the web page. •Interactivityis
Page 18: XHTML, Javascript, AJAX, PHP - Informatika Unsyiahinformatika.unsyiah.ac.id/~viska/pbw/07-AJAX-PHP.pdf · •These events are user actions, they call elements of the web page. •Interactivityis

DatabaseDatabase Stock ExampleStock Example

<!DOCTYPE html PUBLIC ""http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">

<head><title>Stock Script</title>

We have two JavascriptJavascript filesfiles in our example. They are loaded in the <head> <head> section of our HTML file.

<title>Stock Script</title><meta http-equiv="Contentcharset=ISO-

<script type="text/javascript" src="</script><script type="text/javascript" src="</script> </head>...

Stock ExampleStock Example

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN""http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">

<title>Stock Script</title>

example18-2.htm

in our example. They are loaded section of our HTML file.

<title>Stock Script</title>equiv="Content-Type" content="text/html; -8859-1" />

<script type="text/javascript" src="getxmlhttprequest.js">

<script type="text/javascript" src="example18-2.js">

Page 19: XHTML, Javascript, AJAX, PHP - Informatika Unsyiahinformatika.unsyiah.ac.id/~viska/pbw/07-AJAX-PHP.pdf · •These events are user actions, they call elements of the web page. •Interactivityis

DatabaseDatabase Stock ExampleStock Example

<body>

<h2>Fruit Stock Information:</h2><form action="" method="post"><p><label for="strStock">Stock Query: </label><input type="text" name="

example18

We have a query input text fieldtext field

<input type="text" name="</p>

<p><input type="button" value="Check" </p>…

The submit button submit button includes an onclickonclickstartJSstartJS()() function when clicked (example18(example18

Stock ExampleStock Example

<h2>Fruit Stock Information:</h2><form action="" method="post">

<label for="strStock">Stock Query: </label><input type="text" name="strStock" id="strStock"/>

example18-2.htm (continuation…)

and a submit buttonsubmit button

<input type="text" name="strStock" id="strStock"/>

<input type="button" value="Check" onclick="startJS();"/>

onclickonclick event event which invokes the(example18(example18--2.js).2.js).

Page 20: XHTML, Javascript, AJAX, PHP - Informatika Unsyiahinformatika.unsyiah.ac.id/~viska/pbw/07-AJAX-PHP.pdf · •These events are user actions, they call elements of the web page. •Interactivityis

DatabaseDatabase Stock ExampleStock Example

<body>

<h2>Fruit Stock Information:</h2><form action="" method="post"><p><label for="strStock">Stock Query: </label><input type="text" name="

example18

The <div> <div> element defines a sectionsectionthe PHP scriptPHP script.

<input type="text" name="</p>

<p><input type="button" value="Check" </p><div id="strStockResult</form>

</body></html>

Stock ExampleStock Example

<h2>Fruit Stock Information:</h2><form action="" method="post">

<label for="strStock">Stock Query: </label><input type="text" name="strStock" id="strStock"/>

example18-2.htm (continuation…continuation…)

sectionsection used to display the outputoutput from

<input type="text" name="strStock" id="strStock"/>

<input type="button" value="Check" onclick="startJS();"/>

strStockResult"></div>

Page 21: XHTML, Javascript, AJAX, PHP - Informatika Unsyiahinformatika.unsyiah.ac.id/~viska/pbw/07-AJAX-PHP.pdf · •These events are user actions, they call elements of the web page. •Interactivityis
Page 22: XHTML, Javascript, AJAX, PHP - Informatika Unsyiahinformatika.unsyiah.ac.id/~viska/pbw/07-AJAX-PHP.pdf · •These events are user actions, they call elements of the web page. •Interactivityis

AJAX AJAX –– connectconnect to server, to server,

function startJS() {

xhrequest = null;try {

xhrequest = getXMLHttpRequest();}catch(error) {

document.write("Cannot run Ajax code using this browser");}

if(xhrequest != null) {

startJS() startJS() is invoked when the button is clicked.

if(xhrequest != null) {// get form valuesvar strStock = document.getElementById("

var strUrl = "example18-2.php??strStock=" +

xhrequest.onreadystatechange = changePagechangePagexhrequest.open("GETGET", strUrl, true);xhrequest.send(null);

}}...

Null because we have appended the query parameters already

to server, to server, sendsend requestrequest

document.write("Cannot run Ajax code using this browser");

example18-2.js

Checks if AJAX is supported.It checks if the xmlhttprequest

object can be created.

Obtain query data entered on the form

is invoked when the button is clicked.

var strStock = document.getElementById("strStock").value;

strStock=" + strStock;

changePagechangePage;Sets a function that obtains the data output from PHP script

Open a connection to the PHP script, then pass the data

PHP script file + User’s query

Null because we have appended the

Page 23: XHTML, Javascript, AJAX, PHP - Informatika Unsyiahinformatika.unsyiah.ac.id/~viska/pbw/07-AJAX-PHP.pdf · •These events are user actions, they call elements of the web page. •Interactivityis

AJAX AJAX –– obtain output obtain output

function changePage() {if (xhrequest.readyState == 44 && xhrequest.status ==

var strResponse strResponse = xhrequest.responseTextdocument.getElementById("strStockResult

}

example18

changePage() obtains the data output obtains the data output then stores it into a variable named

}}

The data is then injected into the section defined in the HTML. This is accomplished using the innerHTML methodinnerHTML method.

obtain output obtain output from serverfrom server

&& xhrequest.status == 200200) {responseText;

strStockResult").innerHTML = strResponsestrResponse;

example18-2.js (continuation…)

Check if data is available

obtains the data output obtains the data output from the PHP script then stores it into a variable named strResponse.

The data is then injected into the strStockResult <div> <div> section defined in the HTML. This is accomplished using the

Retrieve response from the server

Page 24: XHTML, Javascript, AJAX, PHP - Informatika Unsyiahinformatika.unsyiah.ac.id/~viska/pbw/07-AJAX-PHP.pdf · •These events are user actions, they call elements of the web page. •Interactivityis

• an objectobject used both for making the retrieving 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 state of availability of data given by the readyState attribute of

XMLHttpRequestXMLHttpRequest

0: not initialized. 1: connection established. 2: request received. 3: answer in process. 4: finished.

given by the readyState attribute of

only the last one is really useful!

States of readyStatereadyState

used both for making the XMLHttpRequest and response

We have to wait for the data to be available to process it.

state of availability of data state of availability of data is attribute of XMLHttpRequestXMLHttpRequest.

XMLHttpRequestXMLHttpRequest objectobject

: not initialized. : connection established. : request received. : answer in process.

attribute of XMLHttpRequestXMLHttpRequest.

only the last one is really useful!

readyStatereadyState

Page 25: XHTML, Javascript, AJAX, PHP - Informatika Unsyiahinformatika.unsyiah.ac.id/~viska/pbw/07-AJAX-PHP.pdf · •These events are user actions, they call elements of the web page. •Interactivityis

getXMLHttpRequestgetXMLHttpRequest

function getXMLHttpRequest() {var xhrequest = null;

if(window.XMLHttpRequestXMLHttpRequest) {

// If IE7, Mozilla, Safari, etc: Use native object

getxmlhttprequest.js

// If IE7, Mozilla, Safari, etc: Use native objecttry {

xhrequest = new XMLHttpRequest()return xhrequest;

}catch(exception) {

// OK, just carry on looking}

}

Our Javascript needs to be able to acquire the appropriate type of depending on the browser the script is running in.

getXMLHttpRequestgetXMLHttpRequest() () –– useruser--defineddefined

// If IE7, Mozilla, Safari, etc: Use native object

The window object represents an open window in a browser.

Check if this property is present

// If IE7, Mozilla, Safari, etc: Use native object

XMLHttpRequest();

Continued...Continued...

Our Javascript needs to be able to acquire the appropriate type of XMLHttpRequest object, depending on the browser the script is running in.

Use native scripting

Page 26: XHTML, Javascript, AJAX, PHP - Informatika Unsyiahinformatika.unsyiah.ac.id/~viska/pbw/07-AJAX-PHP.pdf · •These events are user actions, they call elements of the web page. •Interactivityis

getXMLHttpRequestgetXMLHttpRequest

else {// ...otherwise, use the ActiveX control for IE5.x and IE6

var IEControls = ["MSXML2.XMLHttp.5.05.0","MSXML2.XMLHttp.4.0","MSXML2.XMLHttp.3.0","MSXML2.XMLHttp"];

for(var i=0; i<IEControls.length; i++) {

try {xhrequest = new ActiveXObject(IEControls[i]);

getxmlhttprequest.js

xhrequest = new ActiveXObject(IEControls[i]);return xhrequest;

}catch(exception) {// OK, just carry on looking}

}// if we got here we didn’t find any matches// if we got here we didn’t find any matchesthrow new Error("Cannot create an XMLHttpRequest");

}}

getXMLHttpRequestgetXMLHttpRequest() () –– useruser--defineddefined

// ...otherwise, use the ActiveX control for IE5.x and IE6

","MSXML2.XMLHttp.4.0","MSXML2.XMLHttp.3.0","MSXML2.XMLHttp"];

(IEControls[i]);

Testing is done starting from the most recent backwards.

(IEControls[i]);

// if we got here we didn’t find any matches// if we got here we didn’t find any matchesthrow new Error("Cannot create an XMLHttpRequest");

Microsoft has developed different implementations of the XMLHttpRequest object over time.

ActiveXObject is an older version implementation.

Page 27: XHTML, Javascript, AJAX, PHP - Informatika Unsyiahinformatika.unsyiah.ac.id/~viska/pbw/07-AJAX-PHP.pdf · •These events are user actions, they call elements of the web page. •Interactivityis
Page 28: XHTML, Javascript, AJAX, PHP - Informatika Unsyiahinformatika.unsyiah.ac.id/~viska/pbw/07-AJAX-PHP.pdf · •These events are user actions, they call elements of the web page. •Interactivityis

<?php$strStock = $_GET$_GET["strStock"];

$dbLocalhost = mysql_connect("localhost", "root", "")

mysql_select_db("stockstock", $dbLocalhost ) or die("Could not find database: " . mysql_error());

$dbRecords = mysql_query("SELECT * FROM$dbLocalhost ) or die("Problem reading table: " . mysql_error());

PHP PHP ScriptScript

$intRecords = mysql_num_rows($dbRecords );

if ($intRecords == 0)echo "<p>Stock Item '$strStock' Unknown.</p>";

else {while ($arrRecords $arrRecords = mysql_fetch_array($dbRecords

$strDescription = $arrRecords $arrRecords ["Description$intQuantity = $arrRecords$arrRecords["Quantity"];echo "<p>$strDescription: Currently we have $intQuantity of boxes.</p>";

}}?>

• Queries the database and outputs the corresponding records found

("localhost", "root", "") or die("Could not connect: " . mysql_error());

) or die("Could not find database: " . mysql_error());

stock stock WHERE Name='$strStock' ", ) or die("Problem reading table: " . mysql_error());

ScriptScript

example18-2.php

);

echo "<p>Stock Item '$strStock' Unknown.</p>";

$dbRecords)) {Description"];

"];echo "<p>$strDescription: Currently we have $intQuantity of boxes.</p>";

Queries the database and outputs the corresponding records found

Contains the user’s query

Table named stockstock

Page 29: XHTML, Javascript, AJAX, PHP - Informatika Unsyiahinformatika.unsyiah.ac.id/~viska/pbw/07-AJAX-PHP.pdf · •These events are user actions, they call elements of the web page. •Interactivityis
Page 30: XHTML, Javascript, AJAX, PHP - Informatika Unsyiahinformatika.unsyiah.ac.id/~viska/pbw/07-AJAX-PHP.pdf · •These events are user actions, they call elements of the web page. •Interactivityis

Stock Table Stock Table

You need to createcreate your database first using then import the stock.sqlstock.sql file containing the structure and data entries.

IdId is a primary keyprimary key, also set to

Stock Table Stock Table (Structure)(Structure)

your database first using phpMyAdminphpMyAdmin, file containing the structure and data

, also set to auto_incrementauto_increment..

Page 31: XHTML, Javascript, AJAX, PHP - Informatika Unsyiahinformatika.unsyiah.ac.id/~viska/pbw/07-AJAX-PHP.pdf · •These events are user actions, they call elements of the web page. •Interactivityis

Stock Table Stock Table

•You can populate the database easily using •You can import the stock.sqlstock.sql file containing the structure and initial data entries.•You can select the INSERTINSERT tag to add more data entries.

Stock Table Stock Table (data)(data)

You can populate the database easily using phpMyAdminphpMyAdmin..file containing the structure and

tag to add more data entries.

Page 32: XHTML, Javascript, AJAX, PHP - Informatika Unsyiahinformatika.unsyiah.ac.id/~viska/pbw/07-AJAX-PHP.pdf · •These events are user actions, they call elements of the web page. •Interactivityis

Files

•• Images (Images (*.jpg*.jpg))

•• PHP script PHP script ((*.php*.php

•• HTML document HTML document

•• JavascriptJavascript ((*.js*.js

Files

))

*.php*.php))

HTML document HTML document ((*.htm*.htm))

*.js*.js))

Page 33: XHTML, Javascript, AJAX, PHP - Informatika Unsyiahinformatika.unsyiah.ac.id/~viska/pbw/07-AJAX-PHP.pdf · •These events are user actions, they call elements of the web page. •Interactivityis

Zooming photo thumbnail applicationZooming photo thumbnail application

• user is presented with a seriesseriesphotos• Upon moving a mouse over mouse over larger image larger image is displayed.

Zooming photo thumbnail applicationZooming photo thumbnail application

seriesseries of small thumbnails small thumbnails of

mouse over mouse over one of the thumbnails, a

Page 34: XHTML, Javascript, AJAX, PHP - Informatika Unsyiahinformatika.unsyiah.ac.id/~viska/pbw/07-AJAX-PHP.pdf · •These events are user actions, they call elements of the web page. •Interactivityis

Zooming photo thumbnail applicationZooming photo thumbnail application

• Using standard Javascript and (X)HTML would require all of the images to be downloaded whenever a user moves a mouse over an image.

• Using AJAXAJAX, only the images that the user wishes to zoom in on are downloaded and a full page refresh is full page refresh is avoidedavoided

Zooming photo thumbnail applicationZooming photo thumbnail application

Using standard Javascript and (X)HTML would require all of the images to be downloaded whenever a user moves a mouse over an image.

, only the images that the user wishes to zoom in on are avoidedavoided.

Page 35: XHTML, Javascript, AJAX, PHP - Informatika Unsyiahinformatika.unsyiah.ac.id/~viska/pbw/07-AJAX-PHP.pdf · •These events are user actions, they call elements of the web page. •Interactivityis
Page 36: XHTML, Javascript, AJAX, PHP - Informatika Unsyiahinformatika.unsyiah.ac.id/~viska/pbw/07-AJAX-PHP.pdf · •These events are user actions, they call elements of the web page. •Interactivityis

<html><head><style type="text/css">img {

float:right;}</style></head>

CSS float: CSS float: applied on an Image applied on an Image

Image_float.htm

CSS-style definition

<body><p>In the paragraph below, we have added an image with style <b>float:right</b>. The result 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></html>

•Elements are floated horizontally, this means that an element can only be floatedfloated

applied on an Image applied on an Image

Image_float.htm

style definition

Image file

<p>In the paragraph below, we have added an image with style <b>float:right</b>. The result is that the image will float to the right in the paragraph.</p>

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

Elements are floated horizontally, this means that an floatedfloated left or right, not up or down.

Page 37: XHTML, Javascript, AJAX, PHP - Informatika Unsyiahinformatika.unsyiah.ac.id/~viska/pbw/07-AJAX-PHP.pdf · •These events are user actions, they call elements of the web page. •Interactivityis

CSS float: CSS float: applied on an Image applied on an Image applied on an Image applied on an Image

Page 38: XHTML, Javascript, AJAX, PHP - Informatika Unsyiahinformatika.unsyiah.ac.id/~viska/pbw/07-AJAX-PHP.pdf · •These events are user actions, they call elements of the web page. •Interactivityis
Page 39: XHTML, Javascript, AJAX, PHP - Informatika Unsyiahinformatika.unsyiah.ac.id/~viska/pbw/07-AJAX-PHP.pdf · •These events are user actions, they call elements of the web page. •Interactivityis

<script type="text/javascript" src="getxmlhttprequest.js</script><script type="text/javascript" src="example18</script>

<style type="text/css">

#big {float: left;

}

htmlhtml

CSS-style definition

}

#small {float: left;width: 320px;

}

</style></head>

• Embedded CSS-style definition is included to define theStyle of the small thumbnail photos and the larger zoomed image.

getxmlhttprequest.js">

example18-3.js">

htmlhtml

Example18-3.htm

style definition

Image file

style definition is included to define theStyle of the small thumbnail photos and the larger

Page 40: XHTML, Javascript, AJAX, PHP - Informatika Unsyiahinformatika.unsyiah.ac.id/~viska/pbw/07-AJAX-PHP.pdf · •These events are user actions, they call elements of the web page. •Interactivityis

<h2>Zooming Pictures:</h2><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"/>

htmlhtml

Example18

<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.jpg12s.jpg" onmouseover="startJS(12);" alt="small picture"/></div>

<div id="big"><img src="graphics/1l.jpg1l.jpg" width='600' </body></html>

• Each of the thumbnail images is displayed within a division with an id “small”.

Large imageLarge image

<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"/>

htmlhtml

Example18-3.htm (continuation…)(continuation…)

<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"/>

" onmouseover="startJS(12);" alt="small picture"/>

" width='600' alt="large picture"/></div>

Each of the thumbnail images is displayed within a division with an id “small”.

The The altalt attribute provides alternative attribute provides alternative information for an image if a user for information for an image if a user for

some reason cannot view it some reason cannot view it

Page 41: XHTML, Javascript, AJAX, PHP - Informatika Unsyiahinformatika.unsyiah.ac.id/~viska/pbw/07-AJAX-PHP.pdf · •These events are user actions, they call elements of the web page. •Interactivityis
Page 42: XHTML, Javascript, AJAX, PHP - Informatika Unsyiahinformatika.unsyiah.ac.id/~viska/pbw/07-AJAX-PHP.pdf · •These events are user actions, they call elements of the web page. •Interactivityis

AJAX AJAX –– connectconnect to server, to server,

function startJS(intPictureintPicture) {

xhrequest = null;try {

xhrequest = getXMLHttpRequest();}catch(error) {

document.write("Cannot run Ajax code using this browser");}

if(xhrequest != null) {

startJS() startJS() is invoked when the button is clicked.

if(xhrequest != null) {// get form values

var strUrl = "example18-3.php??intPicture=

xhrequest.onreadystatechange = changePagechangePagexhrequest.open("GETGET", strUrl, true);xhrequest.send(null);

}}...

Null because we have appended the query parameters already

to server, to server, sendsend requestrequest

document.write("Cannot run Ajax code using this browser");

example18-2.js

Checks if AJAX is supported.It checks if the xmlhttprequest

object can be created.

Contains a number representing the image the mouse has moved over.

is invoked when the button is clicked.

intPicture=" + intPicture;

changePagechangePage;

object can be created.

Sets a function that obtains the data output from PHP script

Open a connection to the PHP script, then pass the data

PHP script file + User’s query

Null because we have appended the

Page 43: XHTML, Javascript, AJAX, PHP - Informatika Unsyiahinformatika.unsyiah.ac.id/~viska/pbw/07-AJAX-PHP.pdf · •These events are user actions, they call elements of the web page. •Interactivityis

AJAX AJAX –– obtain output obtain output

function changePage() {if (xhrequest.readyState == 44 && xhrequest.status ==

var strResponse strResponse = xhrequest.responseTextdocument.getElementById(“big").innerHTML =

}

example18

changePage() obtains the data output obtains the data output then stores it into a variable named

}}

The data is then injected into the section defined in the HTML. This is accomplished using the innerHTML methodinnerHTML method.

obtain output obtain output from serverfrom server

&& xhrequest.status == 200200) {responseText;").innerHTML = strResponsestrResponse;

example18-3.js (continuation…)

Check if data is available

obtains the data output obtains the data output from the PHP script then stores it into a variable named strResponse.

The data is then injected into the strStockResult <div> <div> section defined in the HTML. This is accomplished using the

Retrieve response from the server

Page 44: XHTML, Javascript, AJAX, PHP - Informatika Unsyiahinformatika.unsyiah.ac.id/~viska/pbw/07-AJAX-PHP.pdf · •These events are user actions, they call elements of the web page. •Interactivityis
Page 45: XHTML, Javascript, AJAX, PHP - Informatika Unsyiahinformatika.unsyiah.ac.id/~viska/pbw/07-AJAX-PHP.pdf · •These events are user actions, they call elements of the web page. •Interactivityis

<?php

$intPicture = $_GET$_GET["intPicture"];

echo "<img src='graphics/$intPicture

?>

PHP PHP ScriptScript

• the PHP script obtains the value of the image the mouse has moved over, passed via the GETGET method and stores it in a variable called $intPicture$intPicture.

• It then outputs the (X)HTML element pointing to the corresponding large image.

Name retrieved via GET

$intPicture" . "l.jpgl.jpg' width='600' />";

ScriptScript

example18-3.php

the PHP script obtains the value of the image the mouse has moved and stores it in a variable called

It then outputs the (X)HTML element pointing to the corresponding

Append an Extension to the file name

Name retrieved via

Page 46: XHTML, Javascript, AJAX, PHP - Informatika Unsyiahinformatika.unsyiah.ac.id/~viska/pbw/07-AJAX-PHP.pdf · •These events are user actions, they call elements of the web page. •Interactivityis

Files

•• Images (Images (*.jpg*.jpg))

•• MySQLMySQL ((*.sql*.sql))

•• PHP script PHP script ((*.php*.php

•• HTML document HTML document

•• JavascriptJavascript ((*.js*.js

Files

))

))

*.php*.php))

HTML document HTML document ((*.htm*.htm))

*.js*.js))

Page 47: XHTML, Javascript, AJAX, PHP - Informatika Unsyiahinformatika.unsyiah.ac.id/~viska/pbw/07-AJAX-PHP.pdf · •These events are user actions, they call elements of the web page. •Interactivityis

Consider developing a website that displays a showing in almost realin almost real--time time customers, sales, etc.

Using AJAXAJAX, we can minimise the effectminimise the effectcontinuously updating graph on the users of your website.

Consider developing a website that displays a graphgraphtime time some data about your

minimise the effectminimise the effect of that continuously updating graph on the users of your website.

Page 48: XHTML, Javascript, AJAX, PHP - Informatika Unsyiahinformatika.unsyiah.ac.id/~viska/pbw/07-AJAX-PHP.pdf · •These events are user actions, they call elements of the web page. •Interactivityis
Page 49: XHTML, Javascript, AJAX, PHP - Informatika Unsyiahinformatika.unsyiah.ac.id/~viska/pbw/07-AJAX-PHP.pdf · •These events are user actions, they call elements of the web page. •Interactivityis

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN""http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">

<head><title>Graph Script</title><meta http-equiv="Content-Type" content="text/html; charset=ISO

<script type="text/javascript" src="getxmlhttprequest.js"></script><script type="text/javascript" src="example18

htmlhtml

<script type="text/javascript" src="example18</script><style type="text/css">#graphBars {

float: left; }

#graphScale {float: left; width: 40px;

}</style></head>

• Embedded CSSdefine the Style of the graphing area

CSS

Defines a CSSthat will display the scale of the chart

//W3C//DTD XHTML 1.1//EN""http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">

Type" content="text/html; charset=ISO-8859-1" />

<script type="text/javascript" src="getxmlhttprequest.js">

<script type="text/javascript" src="example18-4.js">

htmlhtmlExample18-4.htm

<script type="text/javascript" src="example18-4.js">

Embedded CSS-style definition is included to Style of the graphing area

CSS-style definition

Defines a CSS-style for an Image file that will display the scale of the chart

Page 50: XHTML, Javascript, AJAX, PHP - Informatika Unsyiahinformatika.unsyiah.ac.id/~viska/pbw/07-AJAX-PHP.pdf · •These events are user actions, they call elements of the web page. •Interactivityis

<body onloadonload="startJS()startJS();">

<h2>Graph:</h2>

<div id="graph">

</div>

htmlhtml

Example18

a a <div> <div>

</div>

</body></html>

• The <div> <div> section will be populated programmatically via a combination of php script and AJAX.

htmlhtml

Example18-4.htm (continuation…)(continuation…)

<div> <div> section that defines the section that defines the graphing areagraphing area

when the web page is loaded, an when the web page is loaded, an onloadonload event invokes the event invokes the startJS() startJS()

functionfunction

section will be populated programmatically via a combination of php script

Page 51: XHTML, Javascript, AJAX, PHP - Informatika Unsyiahinformatika.unsyiah.ac.id/~viska/pbw/07-AJAX-PHP.pdf · •These events are user actions, they call elements of the web page. •Interactivityis
Page 52: XHTML, Javascript, AJAX, PHP - Informatika Unsyiahinformatika.unsyiah.ac.id/~viska/pbw/07-AJAX-PHP.pdf · •These events are user actions, they call elements of the web page. •Interactivityis

AJAX AJAX –– connectconnect to server, to server,

function startJS( ) {

xhrequest = null;try {

xhrequest = getXMLHttpRequest();}catch(error) {

document.write("Cannot run Ajax!");}

if(xhrequest != null) {if(xhrequest != null) {// get form values

var objDate = new Date();var intSecs = objDate.getTime();

var strUrl = "example18-4.php??intSecs=" + xhrequest.onreadystatechange = changePagexhrequest.open("GET", strUrl, true);xhrequest.send(null);setTimeout("startJS()", 500);

} }}...

Call startJS() function (itself!500 milliseconds

startJS() startJS() is invoked when the button is clicked.

to server, to server, sendsend requestrequest

example18-4.js

Checks if AJAX is supported.It checks if the xmlhttprequest

object can be created.

A Data object is created and used to return the number of seconds

elapsed since 1/1/1970 using the getTime() function

intSecs=" + intSecs;changePage; Sets a function that obtains

the data output from PHP script

Open a connection to the PHP script, then pass the data

We want to force the browser to obtain new data

via the PHP script

itself!) after

is invoked when the button is clicked.

getTime() function

Page 53: XHTML, Javascript, AJAX, PHP - Informatika Unsyiahinformatika.unsyiah.ac.id/~viska/pbw/07-AJAX-PHP.pdf · •These events are user actions, they call elements of the web page. •Interactivityis

AJAX AJAX –– obtain output obtain output

function changePage() {if (xhrequest.readyState == 44 && xhrequest.status ==

var strResponse strResponse = xhrequest.responseTextdocument.getElementById(“graph").innerHTML =

}

example18

changePage() obtains the data output obtains the data output then stores it into a variable named

}}

The data is then injected into the in the HTML. This is accomplished using the methodmethod.

Retrieve response from the server

obtain output obtain output from serverfrom server

&& xhrequest.status == 200200) {responseText;

").innerHTML = strResponsestrResponse;

example18-4.js (continuation…)

Check if data is available

obtains the data output obtains the data output from the PHP script then stores it into a variable named strResponse.

The data is then injected into the graph <div> <div> section defined in the HTML. This is accomplished using the innerHTML innerHTML

Retrieve response from the server

Page 54: XHTML, Javascript, AJAX, PHP - Informatika Unsyiahinformatika.unsyiah.ac.id/~viska/pbw/07-AJAX-PHP.pdf · •These events are user actions, they call elements of the web page. •Interactivityis
Page 55: XHTML, Javascript, AJAX, PHP - Informatika Unsyiahinformatika.unsyiah.ac.id/~viska/pbw/07-AJAX-PHP.pdf · •These events are user actions, they call elements of the web page. •Interactivityis

<?php$dbLocalhost = mysql_connect("localhost", "root", "") mysql_select_db(“graphgraph", $dbLocalhost ) or die("Could not find database: " . mysql_error());

srand((double) microtime() * 1000000);$intPercentage = rand(0,99);

$dbWriteRecords= mysql_query("INSERT INTO '$intPercentage')", $dbLocalhost) or die("Problem reading table: " . mysql_error());

PHP PHP ScriptScript

$dbRecords = mysql_query("SELECT * FROMor die("Problem reading table: " . mysql_error());$intCount = mysql_num_rows($dbRecords );

if ($intCount > 20) {$intStart = $intCount - 20;$dbRecords = mysql_query(" SELECT * FROM

$dbLocalhost) or die("Problem reading table: " . mysql_error()); }...

• the PHP script queries (INSERT & SELECT) the database and outputs the corresponding records found.

Last 20 entries

Continued...Continued...

("localhost", "root", "") or die("Could not connect: " . mysql_error());

) or die("Could not find database: " . mysql_error());

INSERT INTO percentageValues VALUES ('', or die("Problem reading table: " . mysql_error());

ScriptScriptexample18-4.php

Generate a random number between [0, 99]

percentageValues", $dbLocalhost )

FROM percentageValues LIMIT $intStart, 20", ) or die("Problem reading table: " . mysql_error());

the PHP script queries (INSERT & SELECT) the database and outputs the corresponding records

Table named percentageValuespercentageValues

Last 20 entries

Page 56: XHTML, Javascript, AJAX, PHP - Informatika Unsyiahinformatika.unsyiah.ac.id/~viska/pbw/07-AJAX-PHP.pdf · •These events are user actions, they call elements of the web page. •Interactivityis

$arrPercent = array (0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0);$intSize = count($arrPercent);$intCount = 0;while ($arrRecords= mysql_fetch_array($dbRecords$arrPercent[$intCount++] = $arrRecords["Percentage"];}graph($arrPercent, $intSize);

function graph($arrData, $intSize) { $intBarWidth = 10;

// $intBarSpacing = 10;

PHP PHP ScriptScript

// $intBarSpacing = 10;$intMultiplier = 1.5;

$intSize = count($arrData);echo "<div id='graphScale'><img src='graphics/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='" . * $intMultiplier . "'>";

}}echo "</div>";

}?>

• the graph function uses 2 <div> sections to define the scale and the graphing area.

= array (0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0);

$dbRecords)) {["Percentage"];

ScriptScriptexample18-4.php

(continuation…)

Fetch the records

A field in the table

<img src='graphics/scale.gif' width='27' height='150' /></div>";

' width='0' height='" . 99 * $intMultiplier . "'>";for($intCount=0; $intCount<$intSize; $intCount++) {{

' width='$intBarWidth' height='" . $arrData[$intCount]

the graph function uses 2 <div> sections to define the scale and the graphing area.

Generate a graph by displaying an image repetitively

Page 57: XHTML, Javascript, AJAX, PHP - Informatika Unsyiahinformatika.unsyiah.ac.id/~viska/pbw/07-AJAX-PHP.pdf · •These events are user actions, they call elements of the web page. •Interactivityis
Page 58: XHTML, Javascript, AJAX, PHP - Informatika Unsyiahinformatika.unsyiah.ac.id/~viska/pbw/07-AJAX-PHP.pdf · •These events are user actions, they call elements of the web page. •Interactivityis

jqueryjquery

jQueryjQuery is a library of JavaScript Functions.

jQueryjQuery is a lightweight "write less, do more"

The jQueryjQuery library contains the following features:

HTML element selections

HTML element manipulation

CSS manipulation

HTML event functions

JavaScript Effects and animations

HTML DOM traversal and modification

AJAX

Utilities

jqueryjquery

is a library of JavaScript Functions.

is a lightweight "write less, do more" JavaScript libraryJavaScript library.

library contains the following features:

animations

HTML DOM traversal and modification

http://w3schools.com/jquery/jquery_intro.asp

Page 59: XHTML, Javascript, AJAX, PHP - Informatika Unsyiahinformatika.unsyiah.ac.id/~viska/pbw/07-AJAX-PHP.pdf · •These events are user actions, they call elements of the web page. •Interactivityis

jqueryjquery

The jQuery library is stored in a singlesinglejQuery functions.

It can be added to a web page with the following mark

<head><script type="text/javascript" src="<script type="text/javascript" src="

</head>

Note:Note: the <script> tag should be inside the page's the <script> tag should be inside the page's <head> <head> section.section.

jqueryjquery

JavaScript file, containing all the

It can be added to a web page with the following mark-up:

<script type="text/javascript" src="jquery.jsjquery.js"></script>

http://w3schools.com/jquery/jquery_intro.asp

<script type="text/javascript" src="jquery.jsjquery.js"></script>

the <script> tag should be inside the page's the <script> tag should be inside the page's

Jquery library

Page 60: XHTML, Javascript, AJAX, PHP - Informatika Unsyiahinformatika.unsyiah.ac.id/~viska/pbw/07-AJAX-PHP.pdf · •These events are user actions, they call elements of the web page. •Interactivityis

JqueryJquery

If you don't want to store the jQuery library on your own computer, you can use the hosted jQuery library from Google or Microsoft.

<head><script type="text/javascript" <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>

</head>

Note:Note: the <script> tag should be inside the page's the <script> tag should be inside the page's

<head><script type="text/javascript" src="http://ajax.microsoft.com/ajax/jquery/jquery

</head>

librarylibrary

If you don't want to store the jQuery library on your own computer, you can use the hosted jQuery library from

http://w3schools.com/jquery/jquery_intro.asp

src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>

the <script> tag should be inside the page's the <script> tag should be inside the page's <head> <head> section.section.

Jquery library

src="http://ajax.microsoft.com/ajax/jquery/jquery-1.4.2.min.js"></script>

Page 61: XHTML, Javascript, AJAX, PHP - Informatika Unsyiahinformatika.unsyiah.ac.id/~viska/pbw/07-AJAX-PHP.pdf · •These events are user actions, they call elements of the web page. •Interactivityis

jQuery uses CSS selectorsselectors to select HTML elements.

Page 62: XHTML, Javascript, AJAX, PHP - Informatika Unsyiahinformatika.unsyiah.ac.id/~viska/pbw/07-AJAX-PHP.pdf · •These events are user actions, they call elements of the web page. •Interactivityis

Recall: Recall: 1. Incorporating CSS1. Incorporating CSS

Example: External style sheet

hr {color:sienna;}p {margin-left:20px;}

mystyle.css

<head><link rel="stylesheet" type="text/css" href="

</head>

p {margin-left:20px;}body {background-image:url("images/back40.gif");}

myHTML.htm

1. Incorporating CSS1. Incorporating CSS

<link rel="stylesheet" type="text/css" href="mystyle.css”>

image:url("images/back40.gif");}

Page 63: XHTML, Javascript, AJAX, PHP - Informatika Unsyiahinformatika.unsyiah.ac.id/~viska/pbw/07-AJAX-PHP.pdf · •These events are user actions, they call elements of the web page. •Interactivityis

•You can apply CSS-style formatting to an HTML element either by using an ID selectorID selector or a Class selectorClass selector.

Recall: Recall: 1. Applying CSS to an HTML 1. Applying CSS to an HTML elementelement

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.•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.. */

}

<h1 id=”ID-name”> Internet programming </h1>

ID selector application:

style formatting to an HTML element either by using an

1. Applying CSS to an HTML 1. Applying CSS to an HTML elementelement

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.Do NOT start an ID name with a number! It will not work in Mozilla/Firefox.

> Internet programming </h1>

Page 64: XHTML, Javascript, AJAX, PHP - Informatika Unsyiahinformatika.unsyiah.ac.id/~viska/pbw/07-AJAX-PHP.pdf · •These events are user actions, they call elements of the web page. •Interactivityis

•You can apply CSS-style formatting to an HTML element either by using an selectorselector or a Class Class selectorselector.

Recall: Recall: 22aa. Applying CSS to an HTML . Applying CSS to an HTML elementelement

class SELECTOR

• The class selector is used to specify a style for a group of elements. Unlike the id selector, 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 Syntax:General Syntax:

.class-name{

Property:value;Property:value;/*... and so on.. */

}

<h1 class=”class-name”> Internet programming </h1><p class=”class-name”> Dynamic HTML: CSS, HTML, DOM, Javascript </p>

class selector application:

style formatting to an HTML element either by using an ID ID

. Applying CSS to an HTML . Applying CSS to an HTML elementelement

The class selector is used to specify a style for a group of elements. Unlike the id selector, 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 "."

> Internet programming </h1>> Dynamic HTML: CSS, HTML, DOM, Javascript </p>

Page 65: XHTML, Javascript, AJAX, PHP - Informatika Unsyiahinformatika.unsyiah.ac.id/~viska/pbw/07-AJAX-PHP.pdf · •These events are user actions, they call elements of the web page. •Interactivityis

•You can apply CSS-style formatting to an HTML element either by using an selectorselector.

Recall: Recall: 22bb. Applying CSS to an HTML . Applying CSS to an HTML elementelement

class SELECTOR

• You can also specify that only specific HTML elements should be affected by a class.

General Syntax:General Syntax:/* this class selector is only applicable to paragraphs*/

p.class-name{

Property:value;Property:value;/*... and so on.. */

}

<p class=”class-name”> Dynamic HTML: CSS, HTML, DOM, Javascript </p>

class selector application:

style formatting to an HTML element either by using an ID selectorID selector or a Class Class

. Applying CSS to an HTML . Applying CSS to an HTML elementelement

You can also specify that only specific HTML elements should be affected by a

/* this class selector is only applicable to paragraphs*/

name

> Dynamic HTML: CSS, HTML, DOM, Javascript </p>

Page 66: XHTML, Javascript, AJAX, PHP - Informatika Unsyiahinformatika.unsyiah.ac.id/~viska/pbw/07-AJAX-PHP.pdf · •These events are user actions, they call elements of the web page. •Interactivityis

jqueryjquery

The jQuery library is stored a singlesingle JavaScript filejQuery 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".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 with class="test".

jqueryjquery

JavaScript file, containing all the

Demonstrates the jQuery hide() function, hiding the current HTML element.

Demonstrates the jQuery hide() function, hiding the element with id="test".

http://w3schools.com/jquery/jquery_syntax.asp

Demonstrates the jQuery hide() function, hiding the element with id="test".

Demonstrates the jQuery hide() function, hiding all <p> elements.

Demonstrates the jQuery hide() function, hiding all elements with

Page 67: XHTML, Javascript, AJAX, PHP - Informatika Unsyiahinformatika.unsyiah.ac.id/~viska/pbw/07-AJAX-PHP.pdf · •These events are user actions, they call elements of the web page. •Interactivityis

jqueryjquery

jQuery uses XPath expressions to select elements with given attributes.

$("[href]") select all elements with an href attribute.

$("[href='#']") select all elements with an href value equal to "#".

$("[href!='#']") select all elements with an href attribute NOT equal to "#".

$("[href$='.jpg']") select all elements with an href attribute that ends with ".jpg".

<a href="http://www.massey.ac.nz/~nhreyes"> 159339 </a>

jqueryjquery

jQuery uses XPath expressions to select elements with given attributes.

select all elements with an href attribute.

select all elements with an href value equal to "#".

select all elements with an href attribute NOT equal to "#".

select all elements with an href attribute that ends with ".jpg".

<a href="http://www.massey.ac.nz/~nhreyes"> 159339 </a>

Page 68: XHTML, Javascript, AJAX, PHP - Informatika Unsyiahinformatika.unsyiah.ac.id/~viska/pbw/07-AJAX-PHP.pdf · •These events are user actions, they call elements of the web page. •Interactivityis

Document Ready FunctionDocument Ready Function

• to prevent any jQuery code from running before the document is finished loading (

$(document).ready(function(){

// jQuery functions go here...

});

Document Ready FunctionDocument Ready Function

code from running before the document is finished loading (is it ready?is it ready?)

function(){

// jQuery functions go here...

Page 69: XHTML, Javascript, AJAX, PHP - Informatika Unsyiahinformatika.unsyiah.ac.id/~viska/pbw/07-AJAX-PHP.pdf · •These events are user actions, they call elements of the web page. •Interactivityis
Page 70: XHTML, Javascript, AJAX, PHP - Informatika Unsyiahinformatika.unsyiah.ac.id/~viska/pbw/07-AJAX-PHP.pdf · •These events are user actions, they call elements of the web page. •Interactivityis

jqueryjquery<html><head>

<script type="text/javascript" src="jquery-1.4.2.min.js<script type="text/javascript">$(document).ready( function() {$("button").click( function() {$("div").load('test1.txt');

} );} );</script>

http://docs.jquery.com/Downloading_jQuery#Current_Release

</script></head><body>

<div><h2>Let AJAX change this text</h2></div><button>Change Content</button>

</body></html>

jqueryjquery

1.4.2.min.js"></script>

jquery1.htm

Jquery library

On click event, load the contents from test1.txttest1.txt into the

div section

http://docs.jquery.com/Downloading_jQuery#Current_Release

</h2></div>

div section

Modify the contents of the <div> <div> section

Page 71: XHTML, Javascript, AJAX, PHP - Informatika Unsyiahinformatika.unsyiah.ac.id/~viska/pbw/07-AJAX-PHP.pdf · •These events are user actions, they call elements of the web page. •Interactivityis

jqueryjquery

The jQuery library is stored as a singlesinglejQuery functions.

The jQuery syntax is tailor made for selecting HTML elements and perform some action on the element(s).

Basic syntax is: $(selector).action()

• $ (dollar sign) to define jQuery• (selector) to "query (or find)" • jQuery action() to be performed on the element(s)

jqueryjquery

singlesingle JavaScript file, containing all the

The jQuery syntax is tailor made for selecting HTML elements and perform some action on the element(s).

http://w3schools.com/jquery/jquery_syntax.asp

$(selector).action()

(dollar sign) to define jQueryto "query (or find)" HTML elementsHTML elements

to be performed on the element(s)

Page 72: XHTML, Javascript, AJAX, PHP - Informatika Unsyiahinformatika.unsyiah.ac.id/~viska/pbw/07-AJAX-PHP.pdf · •These events are user actions, they call elements of the web page. •Interactivityis
Page 73: XHTML, Javascript, AJAX, PHP - Informatika Unsyiahinformatika.unsyiah.ac.id/~viska/pbw/07-AJAX-PHP.pdf · •These events are user actions, they call elements of the web page. •Interactivityis

<html><head><script type="text/javascript" src="jquery-1.4.2.min.js"></script><script type="text/javascript">$(document).ready(function(){$(".flip").click(function(){

$(".panel").slideToggle("slow");});

});</script><style type="text/css"> div.panel,p.flip

jqueryjquery

div.panel,p.flip{margin:0px;padding:5px;text-align:center;background:#e5eecc;border:solid 1px #c3c3c3;}div.panel{height:120px;display:none;}</style></head>…

Do not show the panel initially

Settings for both the panel and flip classes

1.4.2.min.js"></script>

jqueryjquery

Jquery library

On click event, (toggle) slide-up or slide-down the html

element of class panel

Jquery2-slide.htm

element of class panel

Settings for both the panel and flip classes

Page 74: XHTML, Javascript, AJAX, PHP - Informatika Unsyiahinformatika.unsyiah.ac.id/~viska/pbw/07-AJAX-PHP.pdf · •These events are user actions, they call elements of the web page. •Interactivityis

jqueryjquery

<body>

<div class="panel"><p>Special effects like this could be easily incorporated.<p>into your website using jquery! :)</p></div>

<p class="flip">Show/Hide Panel</p>

</body></html>

jqueryjquery

Special effects like this could be easily incorporated.</p>

Jquery2-slide.htm

<div> <div> section of class panel

Serves as a title bar

Page 75: XHTML, Javascript, AJAX, PHP - Informatika Unsyiahinformatika.unsyiah.ac.id/~viska/pbw/07-AJAX-PHP.pdf · •These events are user actions, they call elements of the web page. •Interactivityis

• It is recommended that you put your functions in a separate ..

jqueryjquery

It is recommended that you put your jQuery..jsjs file

jqueryjquery

Page 76: XHTML, Javascript, AJAX, PHP - Informatika Unsyiahinformatika.unsyiah.ac.id/~viska/pbw/07-AJAX-PHP.pdf · •These events are user actions, they call elements of the web page. •Interactivityis

ReferencesReferences

Dynamic Web Application Development using

PHP and MySQL – by Stobart and Parsons

http://w3schools.com/ajax/ajax_intro.asp

http://www.xul.fr/en-xml

http://www.jquery.com

http://w3schools.com/jquery

ReferencesReferences

Dynamic Web Application Development using

by Stobart and Parsons

http://w3schools.com/ajax/ajax_intro.asp

xml-ajax.html

http://w3schools.com/jquery


Recommended