Solved

Coldfusion 8, Ajax,  JQuery Mobile, Dynamic Select List

Posted on 2012-03-25
15
2,068 Views
Last Modified: 2012-03-25
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
Comment
Question by:wsessoms
  • 7
  • 7
15 Comments
 
LVL 15

Expert Comment

by:myselfrandhawa
ID: 37762831
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
 
LVL 7

Expert Comment

by:micropc1
ID: 37763060
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
 

Author Comment

by:wsessoms
ID: 37763400
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
 
LVL 7

Expert Comment

by:micropc1
ID: 37763571
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
 

Author Comment

by:wsessoms
ID: 37763634
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
 
LVL 7

Expert Comment

by:micropc1
ID: 37763653
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
 

Author Comment

by:wsessoms
ID: 37763659
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
Why You Should Analyze Threat Actor TTPs

After years of analyzing threat actor behavior, it’s become clear that at any given time there are specific tactics, techniques, and procedures (TTPs) that are particularly prevalent. By analyzing and understanding these TTPs, you can dramatically enhance your security program.

 

Author Comment

by:wsessoms
ID: 37763661
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
 
LVL 7

Expert Comment

by:micropc1
ID: 37763685
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
 

Author Comment

by:wsessoms
ID: 37763710
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
 
LVL 7

Accepted Solution

by:
micropc1 earned 500 total points
ID: 37763721
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
 

Author Comment

by:wsessoms
ID: 37763723
I will give it a try and let you know how it works out. Thanks for all of your help.
0
 
LVL 7

Expert Comment

by:micropc1
ID: 37763724
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
 
LVL 7

Expert Comment

by:micropc1
ID: 37763822
Btw... You (and i above) spelled suppresswhitespace wrong - might be the problem
0
 

Author Comment

by:wsessoms
ID: 37764124
@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

Featured Post

Find Ransomware Secrets With All-Source Analysis

Ransomware has become a major concern for organizations; its prevalence has grown due to past successes achieved by threat actors. While each ransomware variant is different, we’ve seen some common tactics and trends used among the authors of the malware.

Join & Write a Comment

I spent nearly three days trying to figure out how incorporate OAuth in Coldfusion for the Eventful API. Hopefully, this article will allow Coldfusion Programmers to buzz through the API when they need to. Basically, what this script does is authori…
Introduction A frequently asked question goes something like this:  "I am running a long process in the background and I want to alert my client when the process finishes.  How can I send a message to the browser?"  Unfortunately, the short answer …
The viewer will learn the basics of jQuery, including how to invoke it on a web page. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery.: (CODE)
The viewer will learn the basics of jQuery including how to code hide show and toggles. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery…

706 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

19 Experts available now in Live!

Get 1:1 Help Now