• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 2154
  • Last Modified:

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>
0
wsessoms
Asked:
wsessoms
  • 7
  • 7
1 Solution
 
Gurpreet Singh RandhawaWeb DeveloperCommented:
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
The 14th Annual Expert Award Winners

The results are in! Meet the top members of our 2017 Expert Awards. Congratulations to all who qualified!

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

Join & Write a Comment

Featured Post

Get expert help—faster!

Need expert help—fast? Use the Help Bell for personalized assistance getting answers to your important questions.

  • 7
  • 7
Tackle projects and never again get stuck behind a technical roadblock.
Join Now