2

Basically I am calling from a CFM another CFM which creates an object, calls several methods on this object and logs a user in; otherwise it prints an error on the screen.

Rather then printing the Error, is there a way to take a CFM and have it send a JSON object to the file that called it?

Here's my ajax:

// processing the login form using jQuery
    $("#loginForm").submit(function(event){
        // prevents the form from being submitted, the event is the arg to the function
        event.preventDefault();

        // stores the data from the form into a variable to be used later
        dataString = $("#loginForm").serialize();

        // the AJAX request 
        $.ajax
        ({
            type: "POST",
            url: "/helpers/auth/ldap/login_demo.cfm",
            data: dataString,
            //dataType: "text",
            success: function() 
            {
                location.reload();
            },
            error: function(ErrorMsg) 
            {
                $("#hiddenLoginError").show("fast"); 
                $("#loginForm p").css("margin-bottom","3px");
            }
        });

    });
BenMorel
  • 34,448
  • 50
  • 182
  • 322
Snow_Mac
  • 5,727
  • 17
  • 54
  • 80

2 Answers2

2

On your CFM page, you can have a <cfif> statement that checks whether the page was requested with ajax or not. If it was ajax, return a json object.

<cfset isAjax = (isDefined('cgi.http_x_requested_with') AND lcase(cgi.http_x_requested_with) EQ 'xmlhttprequest')>
...
<cfif isAjax>
  <cfcontent reset="true">{ "result":false, "message": "Login Failure" }<cfabort>
</cfif>

you can then test the response:

dataType: "json",
success: function(rdata) {
  alert(rdata.message);
}
Kevin B
  • 94,570
  • 16
  • 163
  • 180
  • So because it returns data will the success function always be true? – Snow_Mac Jan 13 '12 at 22:18
  • Since it returns a 200 header unless you specify otherwise, it will always run the success function. The data in the success function is based on whatever you returned. In my example, i returned an object with two keys. the first key, `result`, contains a boolean value equal to false. My code shows a sample response for login failed. – Kevin B Jan 13 '12 at 22:23
  • is there a way I can use the success area to set a javascript variable? I've tried myVar = rdata.message; with no luck. – Snow_Mac Jan 13 '12 at 22:25
1

Try:

<cfoutput>#serializeJSON( object )#</cfoutput>
Sam Farmer
  • 4,108
  • 17
  • 20