Populate select list with AJAX

So I'm a real JQUERY beginner, so please take it easy.

I would like to fill a CFSELECT using the data returned from the CFC. Here is my working CFC:

<cfcomponent>
<cffunction name="getDescriptions" access="remote" returnformat="json" returntype="string" output="false">
    <cfquery name="customDescriptions" datasource="#datasource#">
        select description
        from service_descriptions
        where description <>"ADD NEW"
        order by description
     </cfquery>

    <cfset data = serializeJSON(customDescriptions)>
    <cfreturn data>
</cffunction>

      

This is how the data is returned from my CFC:

----> Select from the list <---- Backup MaintenanceMalware BackupMonthly Server MaintenanceNetwatch Alert - High CP usageUNetwatch Alert - Low Disk space on CNetwatch Backup AlertNew Employee TrainingPerform monthly settings on workstationsTesttest2test3test4test5Weekly MaintenanceWhite-List Request

I am trying to use AJAX code to populate a CFSELECT form element.

<cfselect name="descriptionDD4" id="descriptionDD4">
   <option value="add_new">ADD NEW</option>
</cfselect>

      

Here's what I have so far with AJAX, but it doesn't work.

 <script>
       $(document).ready(function CheckAjaxCall()
            {
                $.ajax({
                    type:'POST',
                    url:'cfcs/get_descriptions.cfc?method=getDescriptions',                    
                    dataType:'json',
                    cache:false,
                    success:function(customDescriptions){ 

                $('##descriptionDD4').get(0).options.length = 0;
                $('##descriptionDD4').get(0).options[0] = new Option("--Select--", "0");        

                $.each(description, function(i,item) {
                                    $('##descriptionDD4').get(0).options[$('##descriptionDD4').get(0).options.length] = new Option(item[i].Name, item[i].roll);
                                                                                                                    // Display      Value
                            });

                            },
                            //error:function(){alert("Connection Is Not Available");}
                        });

                        return false;
                    });
            </script>

      

Any help would be greatly appreciated. Thank you. -Brian

0


source to share


1 answer


Note. The default way of CF serializing requests is volatile. Ultimately you may want to use your own movie and return something more typical (and intuitive) like an array of structures. But it's still worth understanding why your current code isn't working, IMO.

Question:

As Scott pointed out , the biggest problem is that your javascript code expects one format, but your cfc returns a different format. You need to change one of them, so they are both in sync. Also, as I mentioned in the comments, using cfselect

won't buy you anything here, so just use plain html select

.

Debugging:

Before you can do anything with the CFC response, you need to understand the sending format. Start simple. Just call cffunction

when the page loads and logs the response to the console. You can wrap everything in a function later after it works.

<script type="text/javascript">
$(document).ready(function(){
    // Important: Must append the parameter "&returnformat=json"
    $.ajax({
       url: 'cfcs/get_descriptions.cfc?method=getDescriptions&returnformat=json'
       , dataType: 'json'
       , success: function(response){
           console.dir(response);
       },
       error: function(msg){
           console.log(msg);
       }
    })
}); 
</script>

      

Using the FF web console, you will see that the result is a structure containing two keys: COLUMNS

and DATA

.

Firefox Web Console



DATA

is a multidimensional array containing the results of your query. It is indexed by row and column number. You can loop through it like in CF. The only difference is that the index will be null based (and of course key names are case sensitive in JS). Add the code below to the function success

and you will see the request values ​​displayed in the web console.

 // display values for debugging purposes
 for (var i = 0; i < response.DATA.length; i++){
    console.log("value in row ["+ i +"] column [0] = "+ response.DATA[i][0]);
 }

      

Application:

Once you understand how to access data, it is simply a matter of using that list to populate the list. You can use a loop for

to add individual parameters, or connect an array DATA

to a function $.each

using the method described here . Since your query only returns one column, I used it for both text and parameter.

$.each(response.DATA, function(i, row){
            // get value in first column ie "description"
            var description = row[0];

            // append new option to list
            $("#descriptionDD4").append($('<option/>', { 
                    value: description,
                    text : description 
            }));
        });

      

All that's left is to wrap the ajax call in a function that you can call where needed. But you should be able to figure this part out on your own.

Hopefully this makes it a little easier to work with remote cffunctions from jQuery.

+2


source







All Articles