Coldfusion 8, Ajax, JQuery Mobile, Dynamic Select List

I need help getting this code to work. I want to dynamically populate a the select options for the select list using Coldfusion 8 and JQuery to perform the Ajax call. Below is the code that I have written but it does not return the <option></option> tags.

Help is appreciated.

HTML ------------------------------------------------------------------------------------------------------------->
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width; user-scalable=0; initial-scale=1.0; maximum-scale=1.0; user-scale=1.0;" />
<title>Trip Calculator</title>
<link href="/jquery-mobile/jquery.mobile-1.0a3.min.css" rel="stylesheet" type="text/css"/>
<link href="/css/mobile.css" rel="stylesheet" type="text/css"/>
<script src="/jquery-mobile/jquery-1.5.min.js" type="text/javascript"></script>
<script src="/jquery-mobile/jquery.mobile-1.0a3.min.js" type="text/javascript"></script>
<script src="/phonegap.js" type="text/javascript"></script>
<script>
$(function() {
           $.ajax({
                      type: "POST",
                      url: "getYears.cfm",
                      cache: false,
                      dataType: "text",
                      success: function(data)
               {
                $(".year").html(data);
            }
       })
})
</script>
</head>
<body>
<div data-role="page" id="listYear">
<div data-role="header">
      <h1>Page One</h1>
</div>    
<div class="page" data-role="content">
       <div data-role="fieldcontain">
       <select name="year" class="year select">
              <option value="" selected="selected" >Select Year</option>  
       </select>  
      </div>            
</div>
</div>
</body>
</html>

CFML ---------------------------------------------------------------------------------------------------------------->
<!---Query Years--->
<cfquery name="allYears" datasource="tripCost">
SELECT * FROM Years
</cfquery>  
<cfoutput>
    <cfloop query="allYears">
         <option value="#year#">#year#</option>
    </cfloop>
</cfoutput>
wsessomsAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Gurpreet Singh RandhawaCEOCommented:
it will not populate the way you are populating u need to refere the option atrribute of the select tag and use the each keyword to fill the values in the option box using jquery
0
micropc1Commented:
Return the data as a JSON array (convert your query using SerializeJSON()) then convert the JSON object to a javascript array using the datatype 'json' in your ajax() method call, then populate the select box by iterating the values in the javascript array and inserting the items by adding new option elements like shown here under 'adding multiple options': http://www.electrictoolbox.com/jquery-add-option-select-jquery/
0
wsessomsAuthor Commented:
I revised the code but I am get the alert "Failed to load Years". Can't figure out why its not working. I hope one of the Experts can see the error that I am making. Below is the new JSON code for CFML and JQuery

When I run the Coldfiusion script directly and add <cfdump var="#data#>  this is the dump that I get from the CFML code

["FY2007","FY2008","FY2009"]

CFML Code------------------------------------------------------------------------->
<!---Query Years--->
<cfquery name="allYears" datasource="#DSN#">
SELECT * FROM Years
</cfquery>

  <cfoutput>
  <cfset counter = 1>
  <cfset years = arrayNew(1)>
  <cfloop query="allYears">
    <cfset years[counter] = "#year#">
      <cfset counter=counter+1>
    </cfloop>
    <cfset data = SerializeJSON(years)>
  </cfoutput>

JQuery ---------------------------------------------------------------------------------->
<script type="text/javascript" charset="utf-8">
$().ready(function() {
    $.ajax({
        type: "POST",
        url: "getYears.cfm",
        data: "{}",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function(data) {
            $("#year").get(0).options.length = 0;
            $("#year").get(0).options[0] = new Option("Select Year", "-1");  
 
            $.each(msg.d, function(index, item) {
                $("#year").get(0).options[$("#year").get(0).options.length] = new Option(item.Display, item.Value);
            });
        },
        error: function() {
            alert("Failed to load Years");
        }
    });
});  
</script>

HTML --------------------------------------------------------------------------------------------->
<select id="year"></select>
0
Ultimate Tool Kit for Technology Solution Provider

Broken down into practical pointers and step-by-step instructions, the IT Service Excellence Tool Kit delivers expert advice for technology solution providers. Get your free copy now.

micropc1Commented:
You need to output the JSON - you're currently setting it to a CF variable. And you aren't adding the option value correctly. Try this...

CFML Code:

<!---Query Years--->
<cfquery name="allYears" datasource="#DSN#">
SELECT * FROM Years
</cfquery>

<cfset years= arrayNew(1)>

<Cfloop query="allYears">
	<cfset years[currentRow] = "#year#">
</cfloop>

<cfoutput>#SerializeJSON(years)#</cfoutput>

Open in new window



JQuery:

	<script charset="utf-8">
	$().ready(function() {
	    $.ajax({
		type: "POST",
		url: "getYears.cfm",
		data: "{}",
		contentType: "application/json; charset=utf-8",
		dataType: "json",
		success: function(data) {
		    $("#year").get(0).options[0] = new Option("Select Year", "-1");   
		    $.each(data, function(index, item) {
			$("#year").get(0).options[$("#year").get(0).options.length] = new Option(item);
		    });
		},
		error: function() {
		    alert("Failed to load Years");
		}
	    });
	});  
	</script>

Open in new window

0
wsessomsAuthor Commented:
Good point I wasn't not out puting the JSON. I changed the code as advised but the results are the same. This is a link to the page with changes to the code above.

What do you thin the problem may be?
0
micropc1Commented:
Probably all the white-space. Click 'view source' on http://trip.nytechcentral.com/pages/cfml/getYears.cfm and you'll see what I mean. I'm seeing...

 
 
 
 
 
 
 
 
	
 
	
 
	
 
 
["FY2007","FY2008","FY2009"]

Open in new window



Did you change your CFML as I did above and only put <cfoutput> tags around the JSON output?
0
wsessomsAuthor Commented:
Yes I did. This is the CMFL

<!---Query Years--->
<cfquery name="allYears" datasource="#dsn#">
SELECT * FROM Years
</cfquery>
<cfset years = arrayNew(1)>
<Cfloop query="allYears">
      <cfset years[currentRow] = "#year#">
</cfloop>
<cfoutput>#SerializeJSON(years)#</cfoutput>
0
wsessomsAuthor Commented:
and this is the JQuery I put in.

<script charset="utf-8">
      $().ready(function() {
          $.ajax({
            type: "POST",
            url: "getYears.cfm",
            data: "{}",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function(data) {
                $("#year").get(0).options[0] = new Option("Select Year", "-1");  
                $.each(data, function(index, item) {
                  $("#year").get(0).options[$("#year").get(0).options.length] = new Option(item);
                });
            },
            error: function() {
                alert("Failed to load Years");
            }
          });
      });  
      </script>
0
micropc1Commented:
You probably don't have whitespace management enabled in the cfadmin. Try wrapping the entire thing in a <cfsilent> or <cfprocessingdirective supresswhitespace="yes"> tag.
0
wsessomsAuthor Commented:
I put in the <cfprocessingdirective supresswhitespace="yes"> tag and now I am getting the alert("Failed to load Years"). Do you think the could be a problem with the code below:

<script charset="utf-8">
      $().ready(function() {
          $.ajax({
            type: "POST",
            url: "getYears.cfm",
            data: "{}",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function(data) {
                $("#year").get(0).options[0] = new Option("Select Year", "-1");  
                $.each(data, function(index, item) {
                  $("#year").get(0).options[$("#year").get(0).options.length] = new Option(item);
                });
            },
            error: function() {
                alert("Failed to load Years");
            }
          });
      });  
      </script>
0
micropc1Commented:
No I'm pretty certain It's an issue with whitespace. I tested it on my machine and it worked just fine. But I have whitespace management enabled...

You know there's a much easier way to do this... just use a CFC...

Years.cfc

<cfcomponent output="false">
	<cffunction name="getYears" access="remote" returnFormat="json"  returnType="Array">
		<!---Query Years--->
		<cfquery name="allYears" datasource="#DSN#">
		SELECT year FROM years
		</cfquery>

		<cfset years = arrayNew(1)>

		<cfloop query="allYears">
			<cfset years[currentRow] = allYears.year>
		</cfloop>

		<cfreturn qArr>
	</cffunction>
</cfcomponent>

Open in new window



jQuery...

<script charset="utf-8">
	$().ready(function() {
	    $.ajax({
		type: "POST",
		url: "Years.cfc?method=getYears",
		data: "{}",
		contentType: "application/json; charset=utf-8",
		dataType: "json",
		success: function(data) {
		    $("#year").get(0).options[0] = new Option("Select Year", "-1");   
		    $.each(data, function(index, item) {
			$("#year").get(0).options[$("#year").get(0).options.length] = new Option(item);
		    });
		},
		error: function() {
		    alert("Failed to load Years");
		}
	    });
	});  
</script>

Open in new window

0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
wsessomsAuthor Commented:
I will give it a try and let you know how it works out. Thanks for all of your help.
0
micropc1Commented:
Be sure to change qArr to years in the CFC. I called it qArr when I tested it, but forgot to change it back for you.
0
micropc1Commented:
Btw... You (and i above) spelled suppresswhitespace wrong - might be the problem
0
wsessomsAuthor Commented:
@micropc1

I had faith that your code worked and that the problem had to be on my end so I looked at the error console in Firefox and found that there were a bunch of errors occurring when jquery.mobile was executing. I am now using http://code.jquery.com/jquery-1.7.2.js to access JQuery and your code works perfectly. It was the implementation of the version of JQuery mobile that was causing all of the problems. Thanks for your help. I do want to use JQuery mobile so I am going to look for the links to it on the internet.

Thanks again Good Work!
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
ColdFusion Language

From novice to tech pro — start learning today.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.