Using AJAX - PowerPoint PPT Presentation

1 / 19
About This Presentation
Title:

Using AJAX

Description:

Example: Interactive Phone Directory. Phone directory stored in MySQL database ... outputText = ' tr td ' name ' /td td ' phone ' /td /tr ... – PowerPoint PPT presentation

Number of Views:104
Avg rating:3.0/5.0
Slides: 20
Provided by: heatherl8
Category:
Tags: ajax | directory | phone | using

less

Transcript and Presenter's Notes

Title: Using AJAX


1
Using AJAX
  • (Asynchronous JavaScript and XML)
  • Heather Lonsdale
  • CS419 Open Source

2
What is AJAX?
  • Traditional websites vs. software applications
  • Require page reload to contact server
  • Less responsive to user actions
  • AJAX blends the line between desktop and web
    applications

3
What is AJAX?
  • Combination of tools
  • An object that allows access to the web server
    without reloading the page
  • XMLHttpRequest
  • A dynamic programming language that can be easily
    integrated into websites
  • JavaScript
  • A format to easily exchange data with the server
  • XML

4
What is it useful for?
  • Anything where the user should expect immediate
    results
  • Form-driven interaction
  • Expanding tree-type structures
  • Voting and rating systems
  • Find/filter as you type, autocompletion

5
Example Interactive Phone Directory
  • Phone directory stored in MySQL database
  • HTML page that takes a users input and
    immediately displays matching entries
  • PHP page which takes data from the query string
    (ex getData.php?texthello
  • Connects to the database and queries it for
    matching names
  • Returns an XML document of names and phone
    numbers

6
Step 1 Make the Database
  • In phpMyAdmin, execute the following SQL query in
    your database
  • CREATE TABLE phonebook (
  • firstName VARCHAR( 50 ) NOT NULL ,
  • lastName VARCHAR( 50 ) NOT NULL ,
  • phone VARCHAR( 13 ) NOT NULL
  • )
  • Insert a few rows with your friends names and
    phone numbers in the format ()- (or
    just make some up)

7
Step 2 Start the HTML Page
  • Start with a blank page with headers and add the
    following elements to the
  • action""
  • Type first or last name
  • Matching entries will appear here as you
    type
  • 6699"

8
Step 3 Connect to the database
  • Create a new page called getInfo.php

ame 'onid_yourname' dbuser
'onid_yourname' dbpass your_password' mysq
l_handle mysql_connect(dbhost, dbuser,
dbpass) or die("Error connecting to database
server") mysql_select_db(dbname,
mysql_handle) or die("Error selecting
database dbname") echo 'Successfully
connected to database!' mysql_close(mysql_handl
e) ?
9
Step 4 Retrieve data from the DB
  • Given the users input, we want to find all first
    and last names starting with input, then order
    them by last name. The SQL query we will use for
    this is
  • SELECT FROM phonebookWHERE firstName LIKE
    inputOR lastName LIKE inputORDER BY
    lastName
  • Note the character is a wildcard.

10
Step 4 (continued)
  • function findNumbers(input)
  • retVal ''
  • sql 'SELECT FROM phonebook
  • WHERE firstName LIKE "'.input.'
  • OR lastName LIKE "'.input.'" ORDER BY
    lastName'
  • result mysql_query(sql)
  • if (result mysql_num_rows(result)0)
  • while (row mysql_fetch_assoc(result))
  • retVal . '
  • '.rowfirstName.
    '.rowlastName.'
  • '.rowphone."\n"
  • else
  • retVal . "No matching entries
    found."
  • retVal . ''
  • return retVal

11
Step 4 (continued)
  • database setup stuff here
  • mysql_select_db(dbname, mysql_handle)
  • or die("Error selecting database dbname")
  • function findNumbers(input)
  • function body here
  • header('Content-Type text/xml')
  • echo findNumbers(_GET'text')
  • mysql_close(mysql_handle)

12
Step 4 Output
  • Example of output from calling getData.php?textj
  • John Doe
  • (971)237-2222
  • Jane Smith
  • (541)737-7777

13
Step 5 JavaScript
  • 3 functions
  • function getHTTPObject()This gets the
    XMLHttpRequest object depending on which browser
    is being used
  • function lookup(text)This takes the users input
    and calls getData.php
  • function getResponse()This handles the response
    from getData.php and fills in the phonebook
    entries on the page

14
getHTTPObject()
  • function getHTTPObject()
  • var xmlhttp
  • /_at_cc_on
  • _at_if (_at__jscript_version 5)
  • try
  • xmlhttp new ActiveXObject("Msxml2.XMLHTTP"
    )
  • catch (e)
  • try
  • xmlhttp new ActiveXObject("Microsoft.XML
    HTTP")
  • catch (E)
  • xmlhttp false
  • _at_else
  • xmlhttp false
  • _at_end _at_/
  • if (!xmlhttp typeof XMLHttpRequest !
    'undefined')
  • try

15
getHTTPObject()
  • The getHTTPObject() function was borrowed from
    Bill Bercik's AJAX tutorial http//www.webpasties
    .com/xmlHttpRequest/
  • After this function, instantiate a new
    XMLHttpRequest object
  • var http getHTTPObject()

16
lookup(text)
  • http.open("GET", "getData.php?text"text,
    true)
  • http.onreadystatechange getResponse
  • http.send(null)
  • The XMLHttpRequest object has an
    onreadystatechange property which is activated
    each time the HTTP ready state changes
  • We want results to be updated as soon as the text
    field is changed, so set its onkeyup property to
    call our lookup(text) function.
  • onkeyup"lookup(this.value)" /

17
getResponse()
  • This is called each time the readyState property
    of the XMLHttpRequest object changes
  • When the ready state is 4, the request is
    complete
  • Our PHP function produces an node if no
    matching entries were found, so we first check
    for that
  • if (http.readyState 4)
  • var xmlDocument http.responseXML
  • var output document.getElementById('output')
  • if (xmlDocument.getElementsByTagName('error')0!
    null)
  • output.innerHTML xmlDocument.getElements
    ByTagName('error')0. firstChild.data

18
getResponse()
  • else //no error
  • var outputText ""
  • for (i0 iry').length i)
  • var entry xmlDocument.getElementsByTagName('en
    try')i
  • var name entry.getElementsByTagName('name')
    0.firstChild.data
  • var phone entry.getElementsByTagName('phone')
    0.firstChild.data
  • outputText ""name""phon
    e""
  • output.innerHTML outputText""

19
Step 6 Open the HTML page
  • http//oregonstate.edu/lonsdalh/cs419/
  • Other links
  • More detailed step-by-step http//oregonstate.edu
    /lonsdalh/cs419/oldpresentation.ppt
  • Full source code http//oregonstate.edu/lonsdalh
    /cs419/ajaxsource.txt
Write a Comment
User Comments (0)
About PowerShow.com