Search code examples
ajaxcoldfusioncfc

Data lookup using Coldfusion, Ajax, and CFC


I'm using a string instead of an integer as a key to do a data lookup on a table using ColdFusion and Ajax. My test is not returning any values and I'm completely stomped. I tried to convert the ajax value to a string.

HTML

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script>
    $(document).ready(function() {
        $("#init").blur(function() {
            alert("This input field has lost its focus.");
            var initVal = JSON.stringify({'$(this).val()'});
            if(initVal != "") {
                $.get("testrun.cfc?method=getuser&init=initVal", function(res) {
                    $("#team").val=res;
                }, "JSON");
            }
        });
    });
</script>

<input type='text' name='init' id='init' /><br>
<input type='text' name='team' id='team'/>

ColdFusion component

<cfcomponent>
  <cffunction name="getuser" access="remote" returntype="string">
    <cfargument name="init" type="string" required="yes">

      <cfquery name="getUser" datasource="#DSN#">
       SELECT       team
         FROM       users
        WHERE       init = <cfqueryparam value = "#arguments.init#" cfsqltype="cf_sql_varchar">
      </cfquery>

    <cfreturn getUser.TEAM /> 
  </cffunction>
</cfcomponent>

Solution

  • The problem is that you are passing the string "initval" in your Ajax call.

    In other words, jQuery will not magically turn

    "testrun.cfc?method=getuser&init=initVal"
    

    into

    "testrun.cfc?method=getuser&init=whateverYouEnteredInTheTextfield"
    

    Pass the value of the variable instead, and leave the URL parameter building to jQuery completely:

    $("#init").blur(function() {
        var initval = $.trim(this.value);
        if (!initval) return;
    
        $.get("testrun.cfc" {
            method: "getuser",
            init: initval
        }).done(function (res) {
            $("#team").val(res);
        });
    });
    

    It helps to open the network tab in your browser's developer tools and look at the Ajax requests as they are happening.