jQuery Ajax and ColdFusion

coldfusion, jquery

Solution

Are you submitting a query string, or a form post? Usually a login is a POST, not a GET. But anyway.

I usually like to post a more structured response, so that you have the possibility to return additional information to the user, like an error message, but the simple true/false example follows. You could just give the method a remote access attribute, like so:

<cfcomponent name="Login">
   <cfset variables.dsn = "mydb" />
   <cffunction name="tryLogin" access="remote" output="false" returntype="boolean">
      <cfargument name="username" type="string" required="true"/>
      <cfargument name="password" type="string" required="true"/>

      <cfset var loginQuery = "" />

      <cfquery name="loginQuery" datasource="#variables.dsn#">
         SELECT * 
         FROM users 
         WHERE 
            username = <cfqueryparam cfsqltype="cf_sql_varchar" value="#arguments.username#"/> 
            AND 
            password = <cfqueryparam cfsqltype="cf_sql_varchar" value="#arguments.password#"/>
      </cfquery>

      <cfif loginQuery.recordcount>
         <cfreturn true />
      <cfelse>
         <cfreturn false />
      </cfif>
   </cffunction>
</cfcomponent>

Now that you've got your CFC, your basic script should work just fine, with a few modifications:

function AttemptLogin(userName, password)
   {
       $.ajax({
                url: 'login.cfc',
                data: {method: 'tryLogin', username: userName, password: password},
                success: function(data) {
                   if (data == true) { alert('true!');} else { alert('false!');}
                }
       });
   };

As mentioned in another answer, if you're returning a complex datatype, like a struct or array, you'll need to specify a returnFormat of 'json' and modify your data arg, like so:

data: {method: 'tryLogin', returnFormat: 'json', username: userName, password: password}

Problem

I am attempting to submit a querystring to a ColdFusion page. I would like the ColdFusion page to return true or false based on whether the login in successful. When my login button is clicked: ``` function AttemptLogin(userName, password) { $.ajax({ url: 'login.cfc&user=' + userName + '&' + 'password=' + password, success: function(data) { $('.result').val(); [Check for true or false here.] } }); }; ``` My ColdFusion page authenticates the password and user name, and returns, but I don't know how to process what it's returning? I am very new to ColdFusion. ``` <cffunction "TryLogin" returntype="boolean"> </cffunction> ``` ..I'm not sure how to return data from the function after it authenticates, yet alone read it once it returns. Anyone dealt with this before? Thanks, George

Original source