BrettC BrettC - 7 months ago 30
Javascript Question

Create Dropdown list from API Query

Attempting to create a script that will pull information from an API requested XML document and put it into a 2D array.

Upon making the Get request

An XML is produced for each user looking like


Each user has a similar looking output stacked on top of each other. How could this be scrubbed into an array? Example, the first array would have 7 "columns" with all shown information with each user having a row.


So I figured it out for anyone looking for an answer to this type of question in the future. Basically, I found out that the API I was trying to reach (not actually "" as shown in the example) did not allow for CORS or jsonp which left me with the only option of using a Proxy.

Shown is an example of code similar to what I ended up using (below), along with the test XML file shown here

A basic explanation of how this works, it uses the proxy to get the XML file and stores it as "xml" found as "function(xml)". Then the XML doc is searched and each section that starts with "User" gets the "FirstName" and "LastName" data pulled from it and appended to dropdown in the HTML section named "yourdropdownbox".

$.ajaxPrefilter( function (options) {
  if (options.crossDomain && {
    var http = (window.location.protocol === 'http:' ? 'http:' : 'https:');
    options.url = http + '//' + options.url;
    //options.url = "" + options.url;

    function (xml) {
        //console.log("> ", xml);
var select = $('#yourdropdownbox');
		select.append('<option value="">Select a User</option>');				
		var FirstNames = $(this).find('FirstName').text();
	  var LastNames = $(this).find('LastName').text();
		select.append("<option value='"+ FirstNames +"'>"+FirstNames+" "+LastNames+"</option>");

<script src="//"></script>

<select id="yourdropdownbox">


As a note, Proxy's are not known for being extremely secure, so watch out what you use this for.

Also, if I wanted to turn the data into an array instead of appending it each time I could have added

    var firstnamesarray = ["0"];
    var lastnamesarry = ["0"];
    var i = 0;

Above the top row of forward-slashes and then replaced:

    var FirstNames = $(this).find('FirstName').text();
    var LastNames = $(this).find('LastName').text();


    firstnamesarry[i] = $(this).find('FirstName').text();
    lastnamesarry[i] = $(this).find('LastName').text();
    i = i+1;

and replaced the "select.append" First & Last Names with

    firstnamearry[i] & lastnamearry[i]

To view a working example, check out the jsfiddle here