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

Lotus Notes Developer
AMS Staffing Solutions
US-OH-Columbus

Justtechjobs.com Post A Job | Post A Resume
Developer News
Get Ready for Microsoft's 'Oslo' Modeling Tool
Latest Linux Hits Networking Flaws
Metasploit 3.2 Offers More 'Evil Deeds'

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
Microsoft Article: Will Hyper-V Make VMware This Decade's Netscape?
Microsoft Article: BitLocker Encryption on Windows Server 2008
Go Parallel Article: Intel Thread Checker, Meet 20 Million LOC
IBM Whitepaper: Innovative Collaboration to Advance Your Business
Internet.com eBook: Real Life Rails
Avaya Article: Call Control XML - Powerful, Standards-Based Call Control
Tripwire Whitepaper: Seven Practical Steps to Mitigate Virtualization Security Risks
Internet.com eBook: The Pros and Cons of Outsourcing
Internet.com eBook: Best Practices for Developing a Web Site
IBM CXO Whitepaper: The 2008 Global CEO Study "The Enterprise of the Future"
Avaya Article: Call Control XML in Action - A CCXML Auto Attendant
Go Parallel Article: James Reinders on the Intel Parallel Studio Beta Program
IBM CXO Whitepaper: Unlocking the DNA of the Adaptable Workforce--The Global Human Capital Study 2008
Adobe Acrobat Connect Pro: Web Conferencing and eLearning Whitepapers
Go Parallel Article: Getting Started with TBB on Windows
HP eBook: Storage Networking , Part 1
MORE WHITEPAPERS, EBOOKS, AND ARTICLES
Webcasts
Go Parallel Video: Intel(R) Threading Building Blocks: A New Method for Threading in C++
HP Video: Is Your Data Center Ready for a Real World Disaster?
Microsoft Partner Portal Video: Microsoft Gold Certified Partners Build Successful Practices
HP On Demand Webcast: Virtualization in Action
Go Parallel Video: Performance and Threading Tools for Game Developers
Rackspace Hosting Center: Customer Videos
Intel vPro Developer Virtual Bootcamp
HP Disaster-Proof Solutions eSeminar
HP On Demand Webcast: Discover the Benefits of Virtualization
MORE WEBCASTS, PODCASTS, AND VIDEOS
Downloads and eKits
Microsoft Download: Silverlight 2 Software Development Kit Beta 2
30-Day Trial: SPAMfighter Exchange Module
Red Gate Download: SQL Toolbelt
Iron Speed Designer Application Generator
Microsoft Download: Silverlight 2 Beta 2 Runtime
MORE DOWNLOADS, EKITS, AND FREE TRIALS
Tutorials and Demos
IBM IT Innovation Article: Green Servers Provide a Competitive Advantage
Microsoft Article: Expression Web 2 for PHP Developers--Simplify Your PHP Applications
MORE TUTORIALS, DEMOS AND STEP-BY-STEP GUIDES
webref The latest from WebReference.com Browse >
Anatomy of an Ajax Application · Popular JavaScript Framework Libraries: An Overview · Controllers: Programming Application Logic - Part 2
Sitemap · Experts · Tools · Services · Email a Colleague · Contact FREE Newsletters 
 The latest from internet.com
MS Access and MySQL · Cisco AutoQoS: VoIP QoS for Mere Mortals · While VoIP Adoption Explodes in Enterprise, Carrier Spending Lags

Created: November 15, 2005

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