PHP - AJAX and XML

AJAX can be used for interactive communication with an XML file. The following example will demonstrate how a web page can fetch information from an XML file with AJAX When a user selects a CD in the dropdown list above, a function called "showCD()" is executed. The function is triggered by the "onchange" event:

Example -

The showCD() function does the following:

  • Check if a CD is selected
  • Create an XMLHttpRequest object
  • Create the function to be executed when the server response is ready
  • Send the request off to a file on the server
  • Notice that a parameter (q) is added to the URL (with the content of the dropdown list)
  • The PHP File

    The page on the server called by the JavaScript above is a PHP file called "getcd.php". The PHP script loads an XML document, "cd_catalog.xml", runs a query against the XML file, and returns the result as HTML:

    Example -

    When the CD query is sent from the JavaScript to the PHP page, the following happens:

  • PHP creates an XML DOM object
  • Find all elements that matches the name sent from the JavaScript
  • Output the album information (send to the "txtHint" placeholder)