AJAX Asynchronous JavaScript and XML - PowerPoint PPT Presentation

1 / 50
About This Presentation
Title:

AJAX Asynchronous JavaScript and XML

Description:

{ try { xmlhttp = new ActiveXObject('Microsoft.XMLHTTP'); } catch (E) { xmlhttp = false; ... Step 10: Try it out! Open your HTML file. ... – PowerPoint PPT presentation

Number of Views:216
Avg rating:3.0/5.0
Slides: 51
Provided by: heatherl8
Category:

less

Transcript and Presenter's Notes

Title: AJAX Asynchronous JavaScript and XML


1
AJAX(Asynchronous JavaScript and XML)
  • By Heather Lonsdale

2
Part 1AJAX in Summary
  • What does it do?

3
The Problem
  • Web and desktop applications are traditionally
    viewed very differently
  • Desktop applications are more responsive to user
    actions
  • Web applications require the page to reload in
    order to retrieve information from the server
  • How do we allow the client computer and the
    server to communicate without reloading the page?

4
How do we solve it?
  • A combination of tools are needed to create a
    more responsive webpage
  • An object that allows access to the web server
    without reloading the page
  • A dynamic programming language that can be easily
    integrated into websites
  • A format to easily exchange data with the server

5
The Solution AJAX
  • Asynchronous
  • The Object XMLHttpRequest
  • Allows direct submitting and retrieving XML data,
    all in the background without reloading
  • JavaScript
  • The Language JavaScript
  • An object-oriented programming language that runs
    on the clients computer
  • and XML
  • The Format XML
  • Extensible Markup Language (XML) is a flexible
    text format that is useful for exchanging data

6
AJAX in brief
  • AJAX allows you to send and retrieve XML data
    from the client computer to the server via the
    XMLHttpRequest object in the JavaScript language.

7
Part 2Installation
  • Where do you get it?
  • How do you install it?

8
No assembly required!
  • AJAX isnt something you download, its a new
    approach to web applications
  • Everything you need is already there!
  • Browsers must have JavaScript enabled
  • IE must have ActiveX enabled
  • For Microsoft ASP.NET applications, you can
    download a free library for AJAX
  • http//ajax.schwarz-interactive.de

9
Part 3Quick Start
  • How do you use it?

10
Step 1 Make the HTML page
  • Copy this code into a new HTML file
  • lt!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0
    Transitional//EN" "http//www.w3.org/TR/xhtml1/DTD
    /xhtml1-transitional.dtd"gt
  • lthtml xmlns"http//www.w3.org/1999/xhtml"gt
  • ltheadgt
  • lttitlegtAJAX Testerlt/titlegt
  • lt/headgt
  • ltbodygt
  • ltinput type"submit" value"Hello, server!" /gt
  • ltbr /gt
  • ltlabelgtMessage from server
  • ltinput name"txtServer" type"text"
    id"txtServer" /gt
  • lt/labelgt
  • lt/bodygt
  • lt/htmlgt

11
Step 1 (Continued)
  • Your page should look something like this

12
Step 2 Add some JavaScript
  • Add an onclick property to the ltinputgt element
    with the value contact server()
  • ltinput type"submit" value"Hello, server!
    onclick"contactServer()" /gt
  • Add JavaScript in the ltheadergt with a function
    called contactServer()
  • ltheadgt
  • lttitlegtAJAX Testerlt/titlegt
  • ltscript language"javascript" type"text/javascrip
    t"gt
  • function contactServer()
  • lt/scriptgt
  • lt/headgt
  • The onclick event handler will call our
    JavaScript function contactServer() when the
    button is clicked.

13
Step 3 XMLHttpRequest
  • For browser compatibility, use the function on
    the right to get the XMLHttpRequest object
  • Copy the code and paste it after your
    contactServer() function
  • function getHTTPObject()
  • var xmlhttp
  • /_at_cc_on
  • _at_if (_at__jscript_version gt 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

14
Step 4 Create a PHP file
  • This file simply prints Hello, world! for the
    purpose of returning something from the server
    via XMLHttpRequest
  • I named my file response.php if you name it
    something different, be sure to use your name in
    future steps.
  • Code for the PHP file
  • lt?php
  • echo Hello, world!
  • ?gt

15
Step 5 Put it all together
  • Create an XMLHttpRequest object by calling the
    getHTTPObject() function after it is created.
  • Add this after the getHTTPObject() function
  • var http getHTTPObject()
  • In the contactServer() function, use the object
    you created to open response.php
  • Add this code within contactServer()
  • http.open("GET", "response.php", true)

16
Step 5 (Continued)
  • The XMLHttpRequest object has an
    onreadystatechange property which is activated
    each time the HTTP ready state changes
  • When the ready state is 4, the request is
    complete
  • So we must set up a method for onreadystatechange
    that waits until the state is 4 to put the
    response text in our text field
  • Create an empty function called getResponse() at
    the beginning of the script block

17
Step 5 (Continued)
  • Set onreadystatechange in the contactServer()
    function, then call http.send(null) to send the
    request
  • function contactServer()
  • http.open("GET", response.php, true)
  • http.onreadystatechange getResponse
  • http.send(null)
  • Make getResponse() fill the textbox with the
    response text when the request is complete
  • function getResponse()
  • if (http.readyState 4)
  • var tBox document.getElementById('txtServer')
  • tBox.value http.responseText

18
Step 6 Press the button!
  • Open the HTML page and press the button. Hello,
    World! (the text from our PHP file) should
    appear in the textbox.

19
Part 4Detailed Use
  • Using AJAX to return XML data from a MySQL
    database

20
Interactive Phone Book
  • The previous example showed a simple way to
    implement AJAX, but obviously its not very
    useful.
  • In this example, you will make a phonebook in a
    MySQL database, then create a webpage that lists
    matching entries as you type!

21
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)

22
Step 2 Start the HTML Page
  • Use the code at the right to create a form with a
    text field and a ltdivgt to hold the table of
    matching results.
  • lt!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0
    Transitional//EN" "http//www.w3.org/TR/xhtml1/DTD
    /xhtml1-transitional.dtd"gt
  • lthtml xmlns"http//www.w3.org/1999/xhtml"gt
  • ltheadgt
  • ltmeta http-equiv"Content-Type"
    content"text/html charsetiso-8859-1" /gt
  • lttitlegtMy Phonebooklt/titlegt
  • lt/headgt
  • ltbodygt
  • ltform id"form1" name"form1" method"post"
    action""gt
  • ltlabelgtType first or last name
  • ltinput type"text" name"textfield" /gt
  • lt/labelgt
  • lt/formgt
  • ltpgtMatching entries will appear here as you
    typelt/pgt
  • ltdiv id"output" style"margin-left10pxcolor00
    6699"gtlt/divgt
  • lt/bodygt
  • lt/htmlgt

23
Step 3 Connect to the database
  • Create a new page called getInfo.php
  • Insert the code to the right in your file to test
    the database connection (using your values where
    necessary)
  • lt?php
  • dbhost 'oniddb.cws.oregonstate.edu'
  • dbname 'onid_yourname'
  • dbuser 'onid_yourname'
  • dbpass your_password'
  • mysql_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_handle)
  • ?gt

24
Step 3 (continued)
  • Open the page. Hopefully the output is
  • Successfully connected to database!
  • If instead you get an error, consult help
    documents from ONID (or your service provider)
  • When you can successfully connect to the
    database, delete the line beginning with echo
    (we dont want error reporting mixed in the
    output)

25
Step 4 Use the DB to retrieve data
  • 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.

26
Step 4 (continued)
  • Use the following php function, which takes a
    string input and executes the query. Insert it
    right before the mysql_close statement.
  • function findNumbers(input)
  • retVal "" //variable containing return value
  • 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)gt0)
  • while (row mysql_fetch_assoc(result))
  • retVal . rowfirstName."
    ".rowlastName." ".rowphone."ltbr /gt"
  • else
  • retVal . "No matching entries found."
  • return retVal

27
Step 4 (continued)
  • Test the function using an input value that you
    know matches entries in your DB.
  • For example, I used
  • echo findNumbers("S")
  • to find all numbers for first or last names
    beginning with the letter S
  • Make sure you get expected values.

28
Step 5 Make output XML
  • Modify the first instance of retVal to include
    the root node, which well call document
  • function findNumbers(input)
  • retVal 'ltdocumentgt'
  • Modify retVal within the while loop to transform
    it into XML data.
  • while (row mysql_fetch_assoc(result))
  • retVal .
  • 'ltentrygtltnamegt'.rowfirstName.
    .rowlastName.'lt/namegt
  • ltphonegt'.rowphone.lt/phonegtlt/entrygt\n

29
Step 5 (continued)
  • Modify the else-statement to return an lterrorgt
    element.
  • This way we can check for an lterrorgt element,
    then return the error message (if it exists)
    instead of data.
  • else
  • retVal . "lterrorgtNo matching entries
    found.lt/errorgt"
  • return retVal
  • Add the header before the echo statement so the
    JavaScript XMLHttpRequest object will recognize
    the data as XML. Finally, close the root
    document node.
  • header('Content-Type text/xml')
  • echo findNumbers(S)
  • echo lt/documentgt

30
Step 6 Back to HTML
  • Add the following script in the ltheadgt element of
    your html page (well fill it in later)
  • ltscript language"javascript" type"text/javascrip
    t"gt
  • function lookup(text)
  • lt/scriptgt
  • 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.
  • ltinput type"text" name"textfield"
    onkeyup"lookup(this.value)" /gt

31
Step 6 (continued)
  • As in Step 3 of the Quick Start tutorial, copy
    the code at the right to get the XMLHttpRequest
    object
  • Use the function to create an instance of the
    object by inserting this line after the function
  • var http getHTTPObject()
  • function getHTTPObject()
  • var xmlhttp
  • /_at_cc_on
  • _at_if (_at__jscript_version gt 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

32
Step 7 Contact getData.php
  • As in Step 5 of the Quick Start tutorial, copy
    the following code in your lookup(text) function.
    By adding the query string (?textlttextgt), we
    will send the text from the user to the php page
    for processing.
  • function lookup(text)
  • http.open("GET", getData.php?texttext,
    true)
  • http.onreadystatechange getResponse
  • http.send(null)
  • And add the getResponse() method
  • function getResponse()
  • if (http.readyState 4)
  • //will fill in response actions here

33
Step 8 Handle the XML Response
  • Our PHP page will return data in an XML format as
    shown in the example below
  • ltdocumentgt
  • ltentrygt
  • ltnamegtSteve Brownlt/namegt
  • ltphonegt(971)237-2222lt/phonegt
  • lt/entrygt
  • ltentrygt
  • ltnamegtJane Smithlt/namegt
  • ltphonegt(541)737-7777lt/phonegt
  • lt/entrygt
  • lt/documentgt

34
Step 8 (continued)
  • In order to parse the XML, we use
    http.responseXML
  • First, we will check for an lterrorgt element. If
    it exists, we print the error.
  • If there is no lterrorgt, we print a table with a
    row for each entry.

35
Step 8 (continued)
  • Insert this code to execute when the response is
    ready
  • if (http.readyState 4)
  • var xmlDocument http.responseXML
  • var output document.getElementById('output')
  • if (xmlDocument.getElementsByTagName('error')0!
    null)
  • output.innerHTML
  • xmlDocument.getElementsByTagName('error')0.fi
    rstChild.data
  • else
  • var outputText "lttablegt"
  • for (i0 iltxmlDocument.getElementsByTagName('en
    try').length i)
  • var entry xmlDocument.getElementsByTagName('e
    ntry')i
  • var name entry.getElementsByTagName('name')0
    .firstChild.data
  • var phone entry.getElementsByTagName('phone')
    0.firstChild.data
  • outputText "lttrgtlttdgt"name"lt/tdgtlttdgt"phone
    "lt/tdgtlt/trgt"
  • output.innerHTML outputText"lt/tablegt"

36
Step 9 PHP page receives input
  • Until now, you used example input to test
    getData.php
  • When we call getData.php from the HTML page, we
    supplied it with the variable text in the query
    string to give it the users input
  • http.open("GET", "getData.php?text"text, true)
  • In getData.php, modify the line that calls
    findNumbers() to retrieve text via the GET
    variable
  • header('Content-Type text/xml')
  • echo findNumbers(_GET'text')
  • echo "lt/documentgt"

37
Step 10 Try it out!
  • Open your HTML file. As you type in the input
    box, corresponding phonebook entries appear!
  • Note that there may be delays in updating the
    list based on server traffic

38
Part 5Benefits
  • What is AJAX good for?

39
For the web surfer
  • Instant gratification
  • Rather than filling out a form/selecting an
    option and waiting for the entire page to reload,
    the results are delivered almost immediately on
    the same page.
  • Website feels more like a program
  • Without the traditional page-by-page navigation,
    websites are more streamlined and responsive to
    user input

40
For the web designer
  • Avoid postback hell in ASP
  • No need to design a form to post back to itself
    and reload (which can really suck)
  • Process data in a separate file
  • More possibilities for website features
  • Good skill to add to a resume
  • Many companies want to use AJAX to improve their
    website and use the latest technology

41
Part 6Best Practices
  • The best ways to use AJAX

42
Separate behavior from presentation
  • Ideally, the application should be divided into 3
    parts
  • HTML file with the webpage
  • A .js file containing the JavaScript handling the
    AJAX request
  • PHP/ASP file to handle the server functions
  • Why?
  • Easier to read and debug code
  • Designers/developers work on different files
  • Can compile JavaScript separately to ensure valid
    syntax

43
Alter content as little as possible
  • Stick to changing a single id or class in the
    HTML
  • Why?
  • Minimize chance for messing things up
  • Make changes to the page obvious for the user

44
Documentation!
  • Treat an AJAX application like a real program and
    document your code!
  • Comment functions, parameters, output,
    dependencies, etc.
  • Preferably code for a specific purpose to avoid a
    lot of irrelevant code
  • Makes it easier to read and debug code

45
Dont misuse it
  • In brief, use AJAX because you should, not
    because you can.
  • AJAX should enhance or build upon your
    application, not complicate it
  • Make sure your changes are good for the user
    experience

46
Part 7Pros Cons
  • The good and bad of AJAX

47
Pros
  • More possibilities for websites
  • New applications with widespread use via the
    internet
  • Can be used for updating or deleting records,
    expanding web forms, returning search queries,
    editing category trees, etc.
  • No more click-and-wait
  • Compatible with all major browsers

48
Cons
  • Usability issues
  • May break the back button
  • Difficult to bookmark at a particular state
  • Response time
  • As noted in the second example, network latency
    may make it seem like nothing is happening
  • Requires JavaScript/ActiveX/ActiveScript enabled
    in browsers

49
Conclusion
50
Oh the possibilities
  • AJAX blurs the line between webpages and desktop
    applications.
  • By communicating with the server without
    reloading the page, web transactions become
    faster and smoother
  • AJAX is a very powerful tool that has the
    potential to change the idea of a website as we
    know it
Write a Comment
User Comments (0)
About PowerShow.com