Link to home
Start Free TrialLog in
Avatar of wsessoms
wsessoms

asked on

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>
Avatar of Coast Line
Coast Line
Flag of Canada image

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
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/
Avatar of wsessoms
wsessoms

ASKER

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>
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

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?
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?
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>
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>
You probably don't have whitespace management enabled in the cfadmin. Try wrapping the entire thing in a <cfsilent> or <cfprocessingdirective supresswhitespace="yes"> tag.
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>
ASKER CERTIFIED SOLUTION
Avatar of Chris Ashcraft
Chris Ashcraft
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
I will give it a try and let you know how it works out. Thanks for all of your help.
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.
Btw... You (and i above) spelled suppresswhitespace wrong - might be the problem
@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!