Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

using jQuery AJAX to post JSON to a CFC

I'm trying to use Jquery/AJAX/JSON with a CFC to send an email (easy right?) After spending many hours trying to find one complete example of how this should work, I'm getting close but am stuck on the last part. My fail is evident.

I am getting an error of "Unsupported Operation. Check application log for more details." coming back from (I think) ColdFusion.

The GET request that generates that message is coming from the following URL:

http://www.dumbass.com/CFIDE/componentutils/cfcexplorer.cfc?method=getcfcinhtml&name=blah.www.test&path=/blah/www/test.cfc

I am able to call my CFC in a browser, which does send a basic test email:

http://servername/test.cfc?method=sendMail

The form post to the CFC is being sent along as such:

method=sendMail&name=BOB&email=bob%40bitchin.com&subject=Message+from+contact+form&message=bob+is+really+bitchin

Here's the jQuery

$.ajax({
    type: "POST",
    url: "test.cfc?method=sendMail",
    data: {
        "name": $("#footer-form #name2").val(),
        "email": $("#footer-form #email2").val(),
        "subject": "Message from contact form",
        "message": $("#footer-form #message2").val()
    },
    dataType: "json",
    success: function(data) {
        if (data.sent == "yes") {
            $("#MessageSent2").removeClass("hidden");
            $("#MessageNotSent2").addClass("hidden");
            $(".submit-button").removeClass("btn-default").addClass("btn-success").prop('value', 'Message Sent');
            $("#footer-form .form-control").each(function() {
                $(this).prop('value', '').parent().removeClass("has-success").removeClass("has-error");
            });
        } else {
            $("#MessageNotSent2").removeClass("hidden");
            $("#MessageSent2").addClass("hidden");
        }
    }
});

Here is the CFC, (not even trying to use the form fields submitted):

 <cfcomponent output="false" access="remote">
   <cffunction name="sendMail" access="remote" returntype="void">
     <cfmail from="[email protected]" 
      to="[email protected]" subject="duh!!!">
      You got mail!
     </cfmail>
  </cffunction>

The AJAX is bringing back the HTML created for the fail message: "Unsupported Operation. Check application log for more details.".

I'm on a shared CF machine and don't have access to the application logs.Is it passing the data as JSON that is causing me grief? Should I use serialize() on the form instead?

Within the AJAX Jquery I have test.cfc?method=sendMail. Should I put the method within the 'data' block of the AJAX call?

I've got fiddler installed, and am looking at headers, but am still at a loss as to why submitting data to a CFC via Jquery and AJAX should be so much of a mystery.

If anyone can straighten me out or point me to a working example, I would be very appreciative.

UPDATE

After reviewing my javascript - I saw that I had a different function also being called by the form submit - which was causing the "Check application log for more details". Here is the function that was causing the issue for me:

 $(document).ready(function () {
            //this function was getting called in addition to one posted     
            // above. 
            $("input#submit1").click(function(){
                console.log('WTF');
                console.log($('form#footer-form').serialize());
                $.ajax({
                    type: "POST",
                    // this is where I wasn't specifying the method!
                    // it should have been test.cfc?method=sendMail
                    url: "test.cfc", //process to mail
                    // still thinking about serialize to make this flexible
                    data: $('form#footer-form').serialize(),
                    success: function(msg){
                        $("#thanks").html(msg) //hide button and show thank you
                        $("#form-content").modal('hide'); //hide popup  
                    },
                    error: function(){
                        alert("failure");
                    }
                });
            });
        });

Here is my updated CFC which is "working":

 <cffunction name="sendMail" access="remote" returnformat="json" returntype="any">
   <cfargument name="name" required="true" />     
   <cfargument name="subject" required="true" />
   <cfargument name="email" required="true" />
   <cfargument name="message" required="true" /> 



      <cfmail from="[email protected]" 
       to="[email protected]"   subject="#subject#">
      Owning it!
     #name# #subject# #email# #message#
      </cfmail>

      <cfset result ='{"sent":"yes"}'> 

    <cfreturn result />

   </cffunction>

The last bit I'm struggling with is how to properly allow the use of returntype="json" and how to create the return value for that to happen. I have returntype="any" because I was getting an error when I had returntype="json". I would like to use returntype = "json". However this:

<cfset result ='{"sent":"yes"}'> 
<cfreturn result />

throws an error. What is the correct way to create a similar structure so I can use returntype="json"? I'm sure in the future I will want to return JSON from CFC's and don't want to have to build the strings manually ... if that makes any sense.

ie

<cfif success>
  <cfset result ='{"sent":"yes"}'> 
<cfelse>
   <cfset result ='{"sent":"no"}'>
</cfif>

How can I make "result" such that I can use returntype="json"?

like image 928
illiquent Avatar asked Apr 10 '16 01:04

illiquent


People also ask

Is it possible to call a ColdFusion CFC via AJAX?

I recently had a friend ask me about using jQuery to call a ColdFusion CFC via AJAX and return a value. It is actually quite easy and fun to do. It requires two files to be created. The two filenames I’m using for this example are: index.cfm and myCFC.cfc but you could easily use your own filenames.

What is Ajax post method in Ajax?

jQuery Ajax Post method, or shorthand, $.post () method makes asynchronous requests to the web server using the HTTP POST method and loads data from the server as the response in the form of HTML, XML, JSON, etc. Given below is the sample of a POST request sent to the server using ajax

Should I roll-your-own JSON with test CFC?

Instead of test.cfc use a test.cfm page. Here is the code for it: Show activity on this post. Yes, definitely do not roll-your-own JSON. However, do not confuse returnType and returnFormat. The returnType is the type of object to return, such as a query, structure, array, etcetera.

How do I send data to a server using Ajax?

The POST method transports data in the request body. Data can be transported in JSON and XML formats. You can use the XMLHttpRequest object (XHR) to communicate with a web server using the AJAX technique. This is the classic way to do AJAX, but it's not the best way now that the Fetch API is supported in modern browsers.


1 Answers

Instead of test.cfc use a test.cfm page. Here is the code for it:

<cfswitch expression="#url.method#">

<cfcase value="sendMail">
     <cfmail from="[email protected]" 
      to="[email protected]" subject="duh!!!">
      You got mail!
     </cfmail>

    <cfset result = structNew()>
    <cfset result['sent'] = true />
    <cfoutput>#SerializeJSON(result)#</cfoutput>

</cfcase>

</cfswitch>

you also need to adjust a bit the javascript

the call should be to

url: "test.cfm?method=sendMail",

and instead of

if (data.sent == "yes") {

you need

if (data.sent) {
like image 167
Alex Baban Avatar answered Oct 17 '22 06:10

Alex Baban