spacer
home / programming / javascript / jf / column14 / 2 To page 1current page
[previous]

Senior Developer
I T Search
US-NE-Kimball

Justtechjobs.com Post A Job | Post A Resume
Developer News
Sir Tim Talks Up Linked Open Data Movement
From L.A. to Vegas With 100GbE
Salesforce Rolls Out Big Summer '08 Update

Developing Web Applications with Ajax, Pt. 3

The first step is connecting to the MySQL database to retrieve the data. This article is focused on JavaScript, so I won't explain how the following code works; you'll need to learn how to connect to a MySQL database in more detail on your own.

<?php
 $user = "admin";
 $pass = "adminpass";
 $host = "localhost";
 $conn = mysql_connect($host, $user, $pass) or die("Unable to connect to MySQL.");
 $db   = mysql_select_db("pets",$conn) or die("Could not select the database.");
 mysql_close($db);
?>

Once you've connected to the database, you'll retrieve the information with a query as below:

<?php
 $user = "admin";
 $pass = "adminpass";
 $host = "localhost";
 $conn = mysql_connect($host, $user, $pass) or die("Unable to connect to MySQL.");
 $db   = mysql_select_db("pets",$conn) or die("Could not select the database.");
 $result = mysql_query("SELECT * FROM `pets`");
  if(mysql_num_rows ($result) == 0){
     die ('Error: no data found in the database.');
  }
  while ($row = mysql_fetch_assoc($result)){
     echo 'Pet: '.$row['pet'].', tasks: '.$row['tasks'].'. ';
  }
 
 mysql_close($db);
?>

This gives you the information you want, but it isn't output properly . We need to change the PHP to spit out the data as XML, not plain text. There are several changes we must make in order for this to occur.

<?php
 header('Content-Type: text/xml');
 echo '<?xml version="1.0" encoding="UTF-8"?>';
 echo "\n<data>\n<pets>\n";
 $user = "admin";
 $pass = "adminpass";
 $host = "localhost";
 $conn = mysql_connect($host, $user, $pass) or die("Unable to connect to MySQL.");
 $db   = mysql_select_db("pets",$conn) or die("Could not select the database.");
 $result = mysql_query("SELECT * FROM `pets`");
  if(mysql_num_rows ($result) == 0){
     die ('Error: no data found in the database.');
  }
  while ($row = mysql_fetch_assoc($result)){
     echo '<'.$row['pet'].' tasks="'.$row['tasks'].'" />'."\n";
  }
  echo "</pets>\n</data>";
 mysql_close($db);
?>

Let's take the above, one line at a time, and analyze how it's outputting the XML. I've color-coded each line to make it easier to understand.

  • The maroon part of the code sends an HTTP header that causes user agents to understand the output of the PHP file to be XML. This is what makes the file appear to be an XML file when you view it in your browser, even though your file has a ".php" extension.
  • The blue part of the code outputs the XML declaration. This is the first line of the XML that I showed you earlier.
  • The green part of the code outputs the first two tags: our root tag, <data> and our <pets> tag, which holds all of the pets.
  • The black part of the code is the toughest part. This is inside a loop that runs until there is no more data in your database. Each time the code runs, it outputs a new node with a tag name of a pet and a tasks attribute. For example, if the first pet in your database is "Cat" and its corresponding task field is "Feed, Water, Comb for fleas," then PHP will output <Cat tasks="Feed, Water, Comb for fleas" /> in the XML document. The "\n" part just puts a new line at the end, so that the XML code isn't all on the same line.
  • The red part of the code closes the </pets> and </data> nodes, which were opened at the beginning of the document. This part is important because the XML must be well-formed in order for it to work well.

Now that we've gotten PHP to output the XML, all we have to do to update the XML is login to our MySQL database and make the changes we want. Pretty cool, agreed? We can use exactly the same JavaScript as in the last article to retrieve this data, because the XML output is exactly the same.

Conclusion

You can extend this further by simply using XML to store and retrieve data. In other words, you can use PHP to write to your XML file and then have JavaScript read that XML file. With Ajax, you can also periodically check to see if that XML file has been updated and, if so, update the page accordingly.

About the Author

Jonathan Fenocchi is a Web developer who primarily works in the fields of Web Design with CSS, client-side scripting with JavaScript, and server-side scripting with PHP. His web site is located at: http://www.slightlyremarkable.com.

home / programming / javascript / jf / column14 / 2 To page 1current page
[previous]



JupiterOnlineMedia

internet.comearthweb.comDevx.commediabistro.comGraphics.com

Search:

Jupitermedia Corporation has two divisions: Jupiterimages and JupiterOnlineMedia

Jupitermedia Corporate Info


Legal Notices, Licensing, Reprints, & Permissions, Privacy Policy.

Advertise | Newsletters | Tech Jobs | Shopping | E-mail Offers

Solutions
Whitepapers and eBooks
IBM eBook: Planning a Service Oriented Architecture
IBM eBook: Choosing the Right Architecture--What It Means for You and Your Business
Microsoft Article: Will Hyper-V Make VMware This Decade's Netscape?
Avaya Article: Using Intelligent Presence to Create Smarter Business Applications
Intel Go Parallel Article: Getting Started with TBB on Windows
Microsoft Article: 7.0, Microsoft's Lucky Version?
Avaya Article: How to Feed Data into the Avaya Event Processor
IBM Article: Developing a Software Policy for Your Organization
Microsoft Article: Managing Virtual Machines with Microsoft System Center
Intel Go Parallel Article: Intel Threading Tools and OpenMP
HP eBook: Storage Networking , Part 1
Microsoft Article: Solving Data Center Complexity with Microsoft System Center Configuration Manager 2007
MORE WHITEPAPERS, EBOOKS, AND ARTICLES
Webcasts
HP Video: StorageWorks EVA4400 and Oracle
HP Webcast: Storage Is Changing Fast - Be Ready or Be Left Behind
Microsoft Silverlight Video: Creating Fading Controls with Expression Design and Expression Blend 2
MORE WEBCASTS, PODCASTS, AND VIDEOS
Downloads and eKits
Red Gate Download: SQL Toolbelt and free High-Performance SQL Code eBook
Iron Speed Designer Application Generator
MORE DOWNLOADS, EKITS, AND FREE TRIALS
Tutorials and Demos
Silverlight 2 App and Walkthrough: Leverage Silverlight 2 with SQL Server and XML
IBM Article: Enterprise Search--Do You Know What's Out There?
HP Demo: StorageWorks EVA4400
Microsoft Article: The Progress and Promise of Deep Zoom
Microsoft How-to Article: Get Going with Silverlight and Windows Live
MORE TUTORIALS, DEMOS AND STEP-BY-STEP GUIDES
webref The latest from WebReference.com Browse >
Book Review: Head First JavaScript · Web Hosting Control Panels · Use Your Blog for Fast Search Engine Rankings
Sitemap · Experts · Tools · Services · Email a Colleague · Contact FREE Newsletters 
 The latest from internet.com
NetApp's Virtual Storage Strategy Crystallizes · F/MC Watch: A Cisco-Centric Approach · Olympic Time Trials Use Wi-Fi Mesh

Created: November 15, 2005

URL: http://webreference.com/programming/javascript/jf/column14/1