Parse XML with jQuery & AJAX for a select list

31 July, 2014 by Tom Elliott

In this tutorial, we will look at parsing XML using an AJAX call within jQuery and how we might generate a drop down (select list) based on the values within the XML file. The JavaScript function we will be using to generate the select option values can be used more than once, making it useful if you have multiple select lists that need to be populated by different XML values.

jQuery is great at making AJAX requests and XML parsing simple. We will make an AJAX call to an XML file and the results will be parsed for each select option specified as a node within the XML. These results will then be used to generate the resulting HTML for our select list.

The XML

Let’s first take a look at a typical XML file that might hold values for a select list. The example here is for X-Men characters (because why not) and saved as xmen.xml. Each character is separated by a ‘character’ XML node and within each node, we have ‘Name’ and ‘ID’ property, where we specify the values that will be used for the select option text and values.

<?xml version="1.0" encoding="utf-8" standalone="yes" ?>
<root>
<heroes>
  <character>
    <Name value="Professor X"/>
    <ID value="1"/>
  </character>
  <character>
    <Name value="Cyclops"/>
    <ID value="2"/>
  </character>
  <character>
    <Name value="Wolverine"/>
    <ID value="3"/>
  </character>
  <character>
    <Name value="Storm"/>
    <ID value="4"/>
  </character>
  <character>
    <Name value="Rogue"/>
    <ID value="5"/>
  </character>
  <character>
    <Name value="Magneto"/>
    <ID value="6"/>
  </character>
</heroes>
</root>

Before moving on, it’s a good idea to make sure you can open the XML file in a web browser to make sure there are no errors.

The HTML

The only HTML required is an empty ‘select’ tag as below

<select name="x-select" id="x-select"></select>

The jQuery

The jQuery functions required to make the AJAX call and parse the XML is below. The first function ‘setSelect’ will take in 3 parameters:

  1. The ID of our select element (in this case ‘x-select’)
  2. The URL for our xml file, relative to the page where the jQuery code resides
  3. The name of the xml node to target.
setSelect('#x-select', 'xml/xmen.xml', 'character');

function setSelect(selectid, xmlpath, xmlnode) {
	var loadingtext = '-- Loading --';
	var loadinghtml = '<option value="">'+loadingtext+'</option>';
	var randomno  = Math.ceil(Math.random()*999);		

	$(selectid).html(loadinghtml);

	$.ajax({
		url: xmlpath+'?=rn'+randomno,
         success: function(xml) {
         	parseSelectXML(xml, selectid, xmlnode)
         },
      error: function (xhr, ajaxOptions, thrownError) {
        alert(xhr.status);
        alert(thrownError);
      }});
}

function parseSelectXML(xml, selectid, xmlnode) {
	var firstoption = '-- Please select --';
	var firsthtml = '<option value="">'+firstoption+'</option>';
	var selecthtml = '';

	$(xml).find(xmlnode).each(function() {
		var selectvalue = $(this).find('ID').attr('value');
		var selecttext = $(this).find('Name').attr('value');
		selecthtml += '<option value="'+selectvalue +'">'+selecttext+'</option>';
	});

	$(selectid).html(firsthtml+selecthtml);
}

Before the AJAX ($.ajax) call is made, we will first set the text within our select to ‘Loading’, so the user knows that something is happening. In most cases, this loading text will only display momentarily so you may wish to remove this. A random number is then generated which will be used in our AJAX call and will help avoid any potential issues with the caching of the XML file.

We also have some error handling that might give us clues to any potential problems when parsing the XML – this could include 404 or parsing errors. Upon successful request, the parseSelectXML function is called. This will set the first option in our select list to ‘Please select’ before parsing the ‘xml’ data sent back from our AJAX call.

The .find() and .each() jquery functions are then used to find and loop through each node in the XML that matches our ‘character’ xml node. The ‘Name’ and ‘ID’ values in our XML are then used to form the HTML code required for each option in the select list.

Finally, the generated HTML for each option is assigned to the select list using the .html() command



Dynamically generate a select list with jQuery, AJAX & PHP »


Leave a Reply

Your email address will not be published. Required fields are marked *

css.php