ajax joining javascript and php 1. asynchronous javascript and xml (without having to refresh) 2

81
AJAX Joining JavaScript and PHP 1

Upload: lorraine-holt

Post on 26-Dec-2015

252 views

Category:

Documents


4 download

TRANSCRIPT

AJAX

Joining JavaScript and PHP

1

Asynchronous Javascript and XML

(without having to refresh)

2

Web Technologies HTML: Powerful but static CSS: decouples presentation from

structure CGI/PHP

Dynamic image creation database management complex calculations dynamic web content creation

CGI problems: In need of seamless integration Slow response

3

Web Technologies cont’d Flash:

Advantage: Visually impressive movies as web sites,

applications, . . . Impressive results from professional designer Powerful tool for professional developer

Disadvantage: few have both skills

DHTML: HTML + CSS + JavaScript Needs more demanding skills from

developers Example: Gowey’s snow

4

Desktop App vs. InternetIssues Desktop Web application

Cross-platform compatibility

difficult simpler to port between browsers

Stability of deployment difficult only a few large-scale browsers

Code maintenance:patch

reinstall package/Install patch;Who are affected?

Single code baseAccessible by all

Speed real-time slow connection speed

Deliverability none Need to refresh/ response

Other problems NA non-cooperating browsers;non-standard browsers

5

Solution: AJAXPopularized by Google’s Gmail in 3/2004

Read messages without page reload Tag messages without page reload Change folders Spell check of messages while being typed Compose messages Check for new mail regularly View news headlines without page reload Search messages without a page reload Add messages to a quick group and view without page reload Save drafts automatically URL does not change when content is updated Feedback to users

Coined by James Garrett 2/2005

Flickr

6

What does AJAX give us?

Making server-side requests with seamless page-loading

Little to no need for full page refreshes.

7

Traditional server request/response model

Web Server

Web page

New Content

On

Web Page

Server Request

Server Response

8

AJAX internet request/response model

Web Server

Web page

Request/Response1

Request/Response2

Multiple server requests can be made from the page without incurring a further page refresh

Request/Response3

9

Http Requests/Responses When a http request is sent, headers

are passed along to let web server know exactly what it is to be serving and how to handle the request.

Most headers are optional The host header is absolutely required

to let the server know what to serve up. Server then decides what response to

return

10

Code Description

200 OK Returned if the document or file in question is found and served correctly

304 NotModified

Returned if a browser has indicated that it has a local, cached copy, and theserver’s copy has not changed from this cached copy

401Unauthorized

Generated if the request in question requires authorization to access therequested document

403 Forbidden Returned if the requested document does not have proper permissions to beaccessed by the requester

404 Not Found Sent back if the file that is attempting to be accessed could not be found (e.g. ifit doesn’t exist)

500 InternalServer Error

Returned if the server that is being contacted has a problem

503 ServiceUnavailable

Generated if the server is too overwhelmed to handle the request

Common Http Response Codes

11

Method

Description

GET The most common means of sending a request; simply requests a specific resource from the server

HEADSimilar to a GET request, except that the response will come

back without the response body; useful for retrieving headers

POST Allows a request to send along user-submitted data (ideal for web-based forms)

PUT Transfers a version of the file request in question

DELETE Sends a request to remove the specified document

TRACE Sends back a copy of the request in order to monitor its progress

OPTIONS Returns a full list of available methods; useful for checking on what methods a server supports

CONNECT A proxy-based request used for SSL tunneling

Http Request Methods

12

What is AJAX really? AJAX is really just a concept A XMLHttpRequest object on the client

side AJAX describes the interaction of the

client-side XMLHttpRequest object with server–side scripts.

XMLHttpRequest object is instantiated and handled differently by two types of browsers: Microsoft IE creates the object as an ActiveX

control Firefox and Safari as a basic JavaScript object

13

XMLHttpRequest behavior

XMLHttpRequest works in the background without the prerequisite page refresh

Once an instance of the XMLHttpRequest object has been created, methods are available to the user

14

XMLHttpRequest Object methods Method Description

abort() Cancels the current request

getAllResponseHeaders() Returns all HTTP headers as a String type variable

getResponseHeader() Returns the value of the HTTP header specified in the method

open() Specifies the different attributes necessary to make a connection to the server; allows you to make selections such as GET and POST, whether to connect asynchronously, and which URL to connect to

setRequestHeader() Adds a label/value pair to the header when sent

send() Sends the current request15

XMLHttpRequest Methods

abort() To stop the request prematurely. Used when you are concerned about

the length of the connection

16

XMLHttpRequest Methods getAllResponseHeaders() To get the full information on all

HTTP headers that are being passed. Date: Thu, 26 Nov 2009 15:47:06 GMT Server: Apache/2.0.53 (Win32) PHP/5.0.3 X-Powered-By: PHP/5.0.3 Content-Length: 527 Keep-Alive: timeout=15, max=98 Connection: Keep-alive Content-Type: text/html

17

XMLHttpRequest Methods getResponseHeader(“headername”)

To obtain the content of a particular piece of the header.

Useful to retrieve a part of the generally large string obtained from a set of headers.

Example: to retrieve size of requested document

getResponseHeader(“Content-Length”)

18

XMLHttpRequest Methods open(“method”, “URL” [, isAsync [[,

“username”][, “password”]]]) to open a connection to a particular file on the server. method parameter : "GET", "POST", or "PUT" (use "GET" when

requesting data and use "POST" when sending data (especially if the length of the data is greater than 512 bytes).

isAsync boolean - specifies whether the request should be handled asynchronously or not. “true” means that script processing carries on after the send() method, without waiting for a response. “false” means that the script waits for a response before continuing script processing. Default is true.

Not all the arguments in the function are required and can be customized depending on the situation.

19

XMLHttpRequest Methods

setRequestHeader(“label”, “value”) To give the header a string label and

the value of the label May only be invoked after the open() Must be used before the send()

20

XMLHttpRequest Methods

send(“content”) Method to send the request to the

server. If request was sent asynchronously, the

response will come back immediately; otherwise after the response is received.

The parameter “content” is optional Helpful for processing forms – to pass the

values of form elements

21

XMLHttpRequest Properties

onreadystatechange readyState responseText responseXML Status statusText

22

XMLHttpRequest PropertiesProperty Description

onreadystatechange

Used as an event handler for events that trigger upon state changes

readyState contains the current state of the object (0: un-initialized, 1: loading, 2: loaded, 3: interactive, 4: complete)

responseText Returns the response in string format

responseXML Returns the response in proper XML format

status Returns the status of the request in numericalformat (regular page errors are returned, suchas the number 404, which refers to a not founderror)

statusText Returns the status of the request, but in stringformat (e.g. a 404 error would return the stringNot Found). 23

onreadystatechange

Event handler that triggers certain block of code of functions when the state changes

Example: When state changes to complete,

execute a function

24

readyState property Provides a description of the part of

process that the current request is Useful for creating individual actions

based on the state of the request Example:

Execute some code when readySate is loading Stop executing when readyState is complete

25

responseText property

responseText property is returned when the request is processed

Example: request a script, the output of the script is returned through this property

Note: most scripts use this property to pass output to the innerHTML property of an element

26

responseXML

Similar to responseText But in XML format

27

Status property

Status property determines the response code – see table of response codes

If the file requested could not be found, the status set to 404

28

responseText

statusText

Textual representation of the status property

Example if status is set to 404, statusText is set to Not Found

29

Example 1

Cross-Browser Usage Accommodating differences between

IE and other browsers Sending a Request to the Server See ex01/ex1.html

30

Check if Browser is IE

Create a boolean variable to check for a valid Internet Explorer instance.

var xmlhttp = false; Use

try catch clauses to check new ActiveXObject

to see if browser is IE31

//Create a boolean variable to check for a valid Internet Explorer instance.

var xmlhttp = false;

//Check if we are using IE.try { //If the Javascript version is greater than 5. xmlhttp = new ActiveXObject("Msxml2.XMLHTTP"); alert ("You are using Microsoft Internet Explorer.");} catch (e) { //If not, then use the older active x object. try {

//If we are using Internet Explorer. xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); alert ("You are using Microsoft Internet Explorer");} catch (E) { //Else we must be using a non-IE browser. xmlhttp = false;}

}

32

//If we are using a non-IE browser, create a javascript instance of the object.

if (!xmlhttp && typeof XMLHttpRequest != 'undefined') {xmlhttp = new XMLHttpRequest();alert ("You are not using Microsoft Internet Explorer");

}

33

Internet Explorer

34

Mozilla Firefox

35

Opera 9.24

36

Mozilla

37

Sending a Request to the Server

Must validate for a proper response Must decide whether to use the GET or

POST method to do so. To retrieve information from the server, use

GET. To send info to server, GET is not very good due to inherent size limitations

To send information to the server, use POST Confirm several things:

what page you want to connect to what area to load the page or script into: object

id

38

Sending a Request to the Server

function makerequest(serverPage, objID) { var obj = document.getElementById(objID); xmlhttp.open("GET", serverPage); xmlhttp.onreadystatechange = function() { // validate for a proper response

if (xmlhttp.readyState == 4 && xmlhttp.status == 200) { obj.innerHTML = xmlhttp.responseText; } } xmlhttp.send(null);}

39

Summary

Create a new XMLHttpRequest object

Use the object to fire a script and Load it into the appropriate

element on the page

40

Using Ajax for Navigation Dynamically load content into a page via the Ajax

method Since Ajax loads the content exactly where you ask it to,

without refreshing the page, you must note exactly where you are loading content.

Problem: people don’t realize that anything has happened on the page.

Hence for Ajax to be used for navigation, not all page layouts will react well to such functionality

Recommendation: For pages that rely upon navigational menus on top of

screen (rather than bottom, in the content, or on the sides) loading the content below it seems to function best.

41

Using Ajax for Navigation in ex1.html

Note: the URL does not change when links are clicked

42

Example 2: ajax/ex02/test.html

ajax/ex02/test.html is a variant of ajax/ex01/ex1.html Cross-browser usage

more detailed in IE checks Checks non-IE browsers first

Open() method Send(null) in both cases Single link vs multiple links

43

Example ex03a

Expanding and Contracting Content Hiding content and exposing it based on

link clicks ( or hovers, or button presses)

Create access to a large amount of content without cluttering the screen. Add a lot of information in a small amount

of space

44

Example ex03a cont’d Use AJAX to expand and contract a

calendar based upon link clicks Components in C:\wamp\www\ajax\

ex03a: HTML ex3_1.html JavaScript functions.js PHP calendar.php note the flag display_errors = Off in php.ini

45

Expanding and Contracting Content

46

ex3_1.html

A + image or – image A link: “My Calendar” Clicking on the image or “My

Calendar” shows or hides the calendar of the current month On click, calls showHideCalendar()

function in functions.js

47

functions.js

Create ActiveXObject object or XMLHttpRequest object depending on client’s browser

showHideCalendar() function If showCalendar variable is true,

make an Ajax call to the server to fetch the calendar.php script

48

calendar.php

Uses the date() function to determine beginning and end dates of current month

Build the calendar

49

Incremental improvements

Ex03a is rather plain Add some color – CSS Add a task recording mechanism Autcomplete

See Ex03b

50

Example 3 Program Structure Ex03b.html includes:

JavaScript functions.js CSS styles.css Components

Create tasks Auto complete – type w, displays Wing

Huen Task box Toggle to show/hide Calendar Calendar

51

Calendar.php with server-side scripting and AJAX

Get the month and year of today Create a table with the proper

month Color

Normal color Mouseover and mouseout color Today’s color

Alternate years and months52

Presentation with CSS

53

Auto Complete with AJAX

Auto-complete makes data entry seamless and effective

54

Two names starting with J

55

Task Creation

56

Improvements made to ex03a

Presentation: styles.css Autocomplete: JavaScript function autocomplete()

to call PHP script autocomplete.php list of hard-coded names in autocomplete.php for

matches On pressing w, “Wing Huen” is displayed. There are two names starting with J, both names will be

prompted when j or J is pressed Task Creation: Add some more functions to

functions.js createform function to call another PHP script

theform.php PHP theform.php

57

JavaScript functions.js Create XMLHttpRequest object xmlhttp

Cross-browser detection Show calendar

var obj = document.getElementById(objID); var serverPage = "calendar.php"; xmlhttp.open("GET", serverPage); obj.innerHTML = xmlhttp.responseText;

Hide calendar document.getElementById(objID).innerHTML = "";

58

Auto-Complete Gmail

When entering email address of receiver, Gmail searches the list of contacts (with AJAX) and drops down a list of all matches

Select one to fill requested field In Ex03b:

Feed a list of objects to an array Display them based on what the user has

entered The user elects a name by clicking

59

Additional functions in functions.js of ex3_1b

Createform() Displays a hidden div beside the cursor Loads a file theform.php through AJAX

Support functions to cleanup and fetch closetask() hides the task window findPosX() and findPosY() return X and Y

positions for the auto-complete functionality

60

Major JS functions for Auto-Complete

autocomplete() checks for the currently inputted string

in text box (via onkeypress event) Passes the string (sstring) to the script

autocomplete.php via $_GET and AJAX If inputted string matches any of the

built-in names, display them for user to select

Setvalue() sets a value to the object for autocomplete div

61

Form Validation in ex3_1c To validate username

Add a Submit button to call JS function validateform

validateform uses AJAX to access PHP script validator.php

validator.php contains the same list of valid usernames, simulating a DB

If a match is found, submit the form If no match, display an error seamlessly The form stays populated

62

Validator adds success message

63

Validator adds failure message

64

Tool Tips in ex03d a little box with information appearing above a properly

placed cursor. In non-Ajax enabled web-sites, they are hard coded or

potentially loaded through some server-side tricks Will use Ajax to dynamically display a box with all

currently assigned tasks when a user hovers over a certain date.

PHP script would have to scour the database and return any instances of tasks associated with said key.

Will just use an array of tasks for now Changes:

calling a checkfortasks function, fired by the onmouseover event

hidetask function, that fires on the onmouseout event Effect: the current date that a user is hovering over will be

passed to the appropriate functions which are located in the functions.js file

65

JS checkfortasks() -> PHP taskchecker.php checkfortasks function will accept a date

and pass it along (via Ajax) to taskchecker.php

taskchecker.php would usually read from a DB and show the appropriate tasks for the current date in a dynamically created hovering div

To simplify, we will use an associative array.

Put in the associative array in $tasks of taskchecker.php

66

function checkfortasks (thedate, e) {theObject = document.getElementById("taskbox");theObject.style.visibility = "visible";

var posx = 0;var posy = 0;

posx = e.clientX + document.body.scrollLeft;posy = e.clientY + document.body.scrollTop;

theObject.style.left = posx + "px";theObject.style.top = posy + "px";

serverPage = "taskchecker.php?thedate=" + thedate;objID = "taskbox";

var obj = document.getElementById(objID);xmlhttp.open("GET", serverPage);xmlhttp.onreadystatechange = function() {

if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {obj.innerHTML = xmlhttp.responseText;

}}

xmlhttp.send(null);} 67

<?php//taskchecker.php//Actual Task dates normally be loaded from a

database.$tasks = array ("2007-11-22" => 'Thanksgiving.',

"2007-11-23" => 'Shopping!!!', "2007-11-19" => 'CS346 Exam2', "2007-11-26" => 'Study AJAX', "2007-11-28" => 'AJAX class 2', "2007-11-30" => 'AJAX class 3');

$outputarr = array ();

//Run through and check for any matches.while ($ele = each ($tasks)){

if ($ele['key'] == $_GET['thedate']){$outputarr[] = $ele['value'];

}}

taskchecker.php part 1

68

//If we have any matches...if (count ($outputarr) > 0) {?> <div class="taskchecker"> <div class="tcpadding"><?php for ($i = 0; $i < count ($outputarr); $i++) {

echo $outputarr[$i] . "<br />"; }?> </div> </div><?php }?>

Taskchecker.php part 2

69

function hidetask () {tObject = document.getElementById("taskbox");

tObject.style.visibility = "hidden";tObject.style.height = "0px";tObject.style.width = "0px";

}

70

71

Integrating Javascript, AJAX, PHP and MySQL Ex4_1.php grabs a random entry from

DB and displays it in an empty field(div) Disables the slot if already filled. Clicking a field in Ex4_1.php calls JS

function grabword Grabword runs AJAX

to retrieve a random item from DB and display it in the field or

disable the field if filled

72

mysql> show databases;+--------------------+| Database |+--------------------+| information_schema || books || cs346 || mailinglist || mysql || products || testdb1 |+--------------------+7 rows in set (0.14 sec)

From MySQL Console

73

mysql> create database ex04a;Query OK, 1 row affected (0.08 sec)

mysql> show databases;+--------------------+| Database |+--------------------+| information_schema || books || cs346 || ex04a || mailinglist || mysql || products || testdb1 |+--------------------+8 rows in set (0.02 sec)

Create a database in WAMPOn cs346, no need to create a database. Just use the one created for you.

74

mysql> use ex04a;Database changedmysql> create table block ( -> blockid int NOT NULL PRIMARY KEY, -> content varchar(20) -> );Query OK, 0 rows affected (0.27 sec)

mysql> show tables;+-----------------+| Tables_in_ex04a |+-----------------+| block |+-----------------+1 row in set (0.00 sec)

Create a table called block in database ex04a

75

mysql> describe block;+---------+-------------+------+-----+---------+-------+| Field | Type | Null | Key | Default | Extra |+---------+-------------+------+-----+---------+-------+| blockid | int(11) | NO | PRI | NULL | || content | varchar(20) | YES | | NULL | |+---------+-------------+------+-----+---------+-------+2 rows in set (0.00 sec)

Check the schema

76

mysql> insert into block values (1, 'frying');Query OK, 1 row affected (0.02 sec)

mysql> insert into block values (2, 'awaits');Query OK, 1 row affected (0.00 sec)

mysql> insert into block values (3, 'similar');Query OK, 1 row affected (0.00 sec)

mysql> insert into block values (4, 'invade');Query OK, 1 row affected (0.00 sec)

mysql> insert into block values (5, 'profiles');Query OK, 1 row affected (0.02 sec)

mysql> insert into block values (6, 'clothes');Query OK, 1 row affected (0.00 sec)

mysql> insert into block values (7, 'riding');Query OK, 1 row affected (0.00 sec)

mysql> insert into block values (8, 'postpone');Query OK, 1 row affected (0.00 sec)

INSERT the entries

77

mysql> select * from block;+---------+----------+| blockid | content |+---------+----------+| 1 | frying || 2 | awaits || 3 | similar || 4 | invade || 5 | profiles || 6 | clothes || 7 | riding || 8 | postpone |+---------+----------+8 rows in set (0.00 sec)

Query the table with a SELECT statement

78

Sequence of events Ex4_1.php displays 8 fields On clicking any field, grabword() in

functions.js is called If field is empty, run AJAX call to

wordgrabber.php to fill it, otherwise blank the field

wordgrabber.php queries the database $querystr = "SELECT content FROM

block ORDER BY RAND() LIMIT 1";79

Running ex4_1.php

80

81