RSS
 

Posts Tagged ‘xml’

Using XML in your jQuery to populate input boxes

11 Aug

In a previous post I wrote about creating XML pages with MySQL data, using PHP. In this article, I’ll explain in simple terms how to parse that XML data and insert some of its values in to your page using jQuery.

I’m going to keep this very simple, as there seem to be very few examples of this on the net. It took me a while to work out a neat way of doing this, and I’m sure someone can improve on things. If so – please let me know in the comments.

First, lets set up an example. A very simple example.

Imagine an invoice. 4 boxes at the top of a grid, with a ‘Save’ button that will add the contents of those boxes to the list below. The fields are such as ‘Item code’, ‘Description’, ‘Quantity’ and ‘Unit Price’. The user enters the values and clicks the ‘Save’ button to add that row to the list and clear the boxes, ready for the next row to be added. For the purposes of what we are doing, we will also want a 5th box (which would usually be hidden) to store the ‘Invoice Detail Id’.

Something like this:

Code Description Quantity Price Hidden ID

Creating this application is all quite trivial for someone experienced in PHP. However, what would be nice is to be able to edit each row without having to re-load the page. Well we can do this quickly and easily using jQuery.

Before we start with the jQuery code, we need to have ready a PHP page that will return valid XML with the details of an invoice detail record. Please see my previous post for some help on how to do this.

This is an example output from the getDetailRow.php file.

<?xml version="1.0" encoding="utf-8" ?>
<invoice>
  <invoiceDetail>
    <invoiceDetailId>10</invoiceDetailId>
    <code>CR282</code>
    <description>Software Support</description>
    <quantity>3</quantity>
    <unitPrice>40</unitPrice>
 </invoiceDetail>
<invoice>

Against each row, add a button labeled ‘Edit’, and attach some jQuery code that calls a function called editDetailRow(detailRowId) – as the grid is built, insert this code in to each button with the parameter of that row’s detail ID.

Assuming that there is only ever one result in the XML output, you could use the following code to insert the values in to your input boxes.

<script type="text/javascript">
function editDetailRow(detailId) {
    //first we need to load the XML data for that detail row
    //if the function is a success it will call the function called processDetail
    $.ajax({
       type: "GET",
       url: "getDetailRow.php?detailId=" + detailId,
       dataType: "xml",
       success: processDetail
     });
}
 
function processDetail(xml) {
    //this function gets the results from the xml file
    //and inserts them in to the boxes
    $(xml).find("invoiceDetail").each(function()   {
        $("#code").val($(this).find("code").text());
        $("#description").val($(this).find("description").text());
        $("#quantity").val($(this).find("quantity").text());
        $("#unitPrice").val($(this).find("unitPrice").text());
        $("#invoiceDetailId").val($(this).find("invoiceDetailId").text());
    });
}
</script>

Yes, it really is that simple. You will need to add a reset button, and make sure you check for a value in the invoiceDetailId when you save (to either call an UPDATE or an INSERT) but thats it.

Hopefully you will find this useful and can use this as the basis for much more complicated XML and jQuery hookup’s.

 

Creating XML in PHP

28 Jul

Quite often I need to create some XML via PHP, pulling data from a MySQL database.

I have tried various methods but I always come back to this. I like the way that I get full control over doing it explicitly, so thought I would share the code. I am using the MySQL PHP class from Ricocheting.

There are loads of examples out there already on the web, but I hope the code below is very easy to understand as it uses simple PHP code.

<?php
 
//pick up required variables
$userName = $_GET['username'];
$password = $_GET['password'];
 
//include the required files
require_once('config.php');
require_once("Database.class.php");
 
// create the $db ojbect
$db = new Database($config['server'], 
	$config['user'], 
	$config['pass'], 
	$config['database'], 
	$config['tablePrefix']);
 
// connect to the server
$db->connect();
 
//build the query
$query = "SELECT * FROM ".$db->pre."useraccount "; 
 
//build the where statements
$where = "WHERE (userAccountId > 0)";
 
if ($userName) {
	$where = " AND (userName = '" . $db->escape($userName). "')";
}
 
if ($password) {
	$where = " AND (password = '" . $db->escape($password). "')";
}
 
//get the FULL record count
$sql2 = "SELECT count(0) AS theCount FROM ".$db->pre."useraccount $where";
 
$countRecRows = $db->query($sql2);
while ($countRecRow = $db->fetch_array($countRecRows)) {
	$recordCount = $countRecRow['theCount'];
}
 
//execute the main query
$countRows = $db->query($query . $where);
 
//set up the php headers so that the page doesnt cache etc
header("Expires: Mon, 26 Jul 1997 05:00:00 GMT" );
header("Last-Modified: " . gmdate( "D, d M Y H:i:s" ) . " GMT" );
header("Cache-Control: no-cache, must-revalidate" );
header("Pragma: no-cache" );
header("Content-type: text/xml");
 
//include the page header info
echo "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n";
 
//begin the xml data
echo "<useraccounts>\n";
 
//set up the result info
echo  "<total>$recordCount</total>\n";
 
//loop through all the records
while ($row = $db->fetch_array($countRows)) { 
	echo "<useraccount id=\"".$row['userAccountId'] ."\">\n";
 
	echo "<username>";
	echo $row['userName'];
	echo "</username>\n";
 
	echo "<fullname>";
	echo $row['fullName'];
	echo "</fullname>\n";
 
	echo "<accesscode><![CDATA[";
	echo $row['accessCode'];
	echo "]]></accesscode>\n";
 
	echo "</useraccount>\n";
}
 
echo "</useraccounts>";
 
//free the result
$db->close();
?>
 
 

XML Output From PHP

28 Jul

Just a quick one. If you want to output XML from your PHP page you need to set the Headers correctly.

Here is the code you need to include, and it has to be before anything else is printed.

<?php
   header ("Content-Type:text/xml");
?>
 
 

A CSV from XML using XSL

10 Jul

I was asked recently to add the ability to export XML data from our web-based facilities management software. This was so our client could write some of their own scripts that would update their Wiki with some information from our database.

This was simple enough, but then I was asked to add CSV functionality to make it easier to code the simple scripts they would be using at their end, which would run nightly via Cron. Once the XML was working, I didn’t want to write another page so instead, I created a XSLT file that transformed the XML in to neatly formatted CSV text.

The code below is all that was really needed (I have chopped it to only use 2 fields). The fields in this example are delimited by double-quotes.

<xsl:for-each select="//media">
"[<xsl:value-of select="@field1"/>]","<xsl:value-of select="@field2"/>"<br/>
</xsl:for-each>