Snow_Mac
Snow_Mac

Reputation: 5797

Coldfusion: Pass json from a CFM to another CFM?

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");
            }
        });

    });

Upvotes: 2

Views: 1585

Answers (2)

Kevin B
Kevin B

Reputation: 95064

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);
}

Upvotes: 2

Sam Farmer
Sam Farmer

Reputation: 4118

Try:

<cfoutput>#serializeJSON( object )#</cfoutput>

Upvotes: 1

Related Questions