-1

I'm trying to submit a form via jquery so that the whole page won't reloads. I'm following the instruction on jQuery.post() guide but so far it's not working. Here's what I'm looking for to complete this task.

  1. Submit the form to a ColdFusion proxy page and from their it will send the data as json via CFHTTP.
  2. During the process of submitting the form, show a progress gif or status.
  3. Somehow, hide or remove the form off of the page.
  4. Show a success or thank you message on the page where the form used to be.

So far the form I have did not even find the values from the input. The error says that "TypeError: $form.find(...).value is not a function". Below is my JavaScript code thus far:

$(function(){
        $("##frmComment##").submit(function(event){
            event.preventDefault();             
            $("##submitResponse").append('<img src="http://st2.india.com/wp-content/uploads/2014/07/ajax-loader.gif" class="progressGif">');


            // Cache $form, we'll use that selector more than once
            var $form=$(this);

            var data = $form.serialize(); //get all the data of form

            //post it
            $.post(
            "/customcf/knowledgeOwl/proxyPost-KB.cfm",
            data,
            //console.log(response),                
            function(response){
                // Success callback.  Remove your progress gif, eg:
                 //$('body').removeClass('in-progress');
                 console.log(response);
                // Remove the spining gif from the div
                $("##submitResponse img:last-child").remove();
                //Remove the feedback form
                $("##frmComment").remove();
                $form.fadeOut('slow', function(){
                    //Add response text to the div
                    $("##submitResponse").append("<h6>Thank you for your feedback.</h6>");
                    $("##submitResponse").html(response).fadeIn('slow');
                });
            });


            });
        })

Here's the project I've setup in JSFiddle. And here's the form.

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>

<form data-abide id="frmComment">
    <div class="row">
        <div class="large-12 medium-12 columns">
            <div class="row" data-equalizer>
                <div class="large-4 medium-4 columns">
                    <div class="row">
                        <div class="large-12 columns">
                            <label>
                                <input type="text" placeholder="Name" name="name" required>
                            </label>
                            <small class="error">Name is required and must be a string.</small>
                        </div>
                    </div>
                    <div class="row">
                        <div class="large-12 columns">
                            <label>
                                <input type="text" placeholder="Email" name="mailfrom" required pattern='.*@.*\..{3}|.*@.*\..{2}'>
                            </label>
                            <small class="error">An email address is required.</small>
                        </div>
                    </div>
                    <div class="row">
                        <div class="large-12 columns">
                            <div class="g-recaptcha" data-sitekey="6LfjNwITABCDPbDHdC5wx6HXRmXtqO3pgUItl-E"></div>
                            <noscript>
                                <div style="width: auto; height: 462px;">
                                    <div style="width: auto; height: 422px; position: relative;">
                                        <div style="width: auto; height: 422px; position: absolute;">
                                            <iframe src="https://www.google.com/recaptcha/api/fallback?k=6LfjNwITABCDPbDHdC5wx6HXRmXtqO3pgUItl-E" frameborder="0" scrolling="no" >
                                            </iframe>
                                        </div>
                                    </div>
                                    <div style="border-style: none; bottom: 12px; left: 25px; margin: 0px; padding: 0px; right: 25px; background: ##f9f9f9; border: 1px solid ##c1c1c1; border-radius: 3px; height: 100px; width: 300px;">
                                        <textarea id="g-recaptcha-response" name="g-recaptcha-response" class="g-recaptcha-response" style="width: 280px; height: 80px; border: 1px solid ##c1c1c1; margin: 10px; padding: 0px; resize: none;"></textarea>
                                    </div>                                                  
                                </div>
                                <br /><br />                                             
                            </noscript>
                        </div>
                    </div>
                </div>
                <div class="large-8 medium-8 columns">
                    <div class="row">
                        <div class="large-12 columns">
                            <textarea id="message" name="message" placeholder="Leave a comment...we love feedback!" rows="5"  required></textarea>                                                  
                        </div>
                    </div>
                    <div class="row">
                        <div class="large-12 columns">
                            <button type="submit" class="tiny right button">Submit</button>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</form>
<div id="submitResponse"></div>

Okay, with some help, I managed to get the jQuery post to send the data to my proxyPost-KB.cfm page but it error out (505) when it hits that page. This is what I have in my proxyPost-KB.cfm page. None of the logs I setup in this CFM page is even get executed either.

<!---
    Make the proxy HTTP request using. When we do this, try to pass along all of the CGI information that was made by the original AJAX request.
--->
<cflog text="CGI: #cgi#" type="Information" file="CGIparameters">
<cfhttp url="https://app.kb.com/api/head/comment.json" method="post" timeout="15" throwonerror="true">
    <!---<cfhttpparam type="body" name="data"value="#serializeJSON(jsonString)#" />--->
    <cfhttpparam type="url" name="_authbykey" value="56ec1f1232131c78636142d6">
    <cfhttpparam type="url" name="project_id" value="55c4ffd123131c527e294fe6">
    <!---<cfhttpparam type="url" name="article_id" value="#artID#">
    <cfhttpparam type="url" name="content" value="#form.message#"/>
    <cfhttpparam type="url" name="public_name" value="#form.name#"/>
    <cfhttpparam type="url" name="public_email" value="#form.mailfrom#"/>--->
    <cfhttpparam type="url" name="status" value="pending"/>

    <!--- Pass along any URL values. --->
    <cfloop item="strKey" collection="#URL#">
        <!---<cfhttpparam type="url" name="public_name" value="#URL[strKey]#" />
        <cfhttpparam type="url" name="public_email" value="#URL[strKey]#" />--->        
        <cflog text="URL: #URL[strKey]#" type="Information" file="CGIparameters">
    </cfloop>
</cfhttp>

<!---
    Get the content as a byte array (by converting it to binary,
    we can echo back the appropriate length as well as use it in
    the binary response stream.
--->
<cfset binResponse = ToBinary(ToBase64( objRequest.FileContent )) />

<!--- Echo back the response code. --->
<cfheader statuscode="#Val( objRequest.StatusCode )#" statustext="#ListRest( objRequest.StatusCode, ' ' )#" />

<!--- Echo back response legnth. --->
<cfheader name="content-length" value="#ArrayLen( binResponse )#" />

<!--- Echo back all response heaers. --->
<!---<cfloop item="strKey" collection="#objRequest.ResponseHeader#">
<!--- Check to see if this header is a simple value. --->
    <cfif IsSimpleValue( objRequest.ResponseHeader[ strKey ] )>

        <!--- Echo back header value. The cfheader tag generate the error "Complex object types cannot be converted to simple values"--->
        <cfheader name="#strKey#" value="#objRequest.ResponseHeader[ strKey ]#" />
        <cflog text="IsSimpleValue: #strKey#" type="Information" file="debugCFLoop">
    </cfif>
</cfloop>--->--->

<!---
    Echo back content with the appropriate mime type. By using
    the Variable attribute, we will make sure that the content
    stream is reset and ONLY the given response will be returned.
--->
<cfcontent type="#objRequest.MimeType#" variable="#binResponse#" />
2myCharlie
  • 1,587
  • 2
  • 21
  • 35
  • 2
    TypeError is here, it's not `$form` but `$(form)` – Sabbin Mar 23 '16 at 18:14
  • Ah! Felt some dumb now...I'l give that a try. – 2myCharlie Mar 23 '16 at 18:16
  • Okay, I tried that and it's still giving me the same error. Plus, the sample code from this page, http://api.jquery.com/jquery.post/, shows it the way I have up there. – 2myCharlie Mar 23 '16 at 18:20
  • Just read this post it may give you pointer to solve the problem the silution is for php but form submission works same way in any technology http://stackoverflow.com/questions/15173965/serializing-and-submitting-a-form-with-jquery-post-and-php – Keshav jha Mar 23 '16 at 18:33
  • Okay, first step is solved, I think. The problem with the error is that it used .value() instead of .val() that's why I got the error $form.value not a function. – 2myCharlie Mar 23 '16 at 19:07
  • Wait....you are sending the form data to a 'ColdFusion proxy page' and then sending the 'data as json via CFHTTP'? You should just send the form data as JSON to begin with and not use the 'ColdFusion proxy page', nor `CFHTTP` – Scott Stroz Mar 23 '16 at 19:24
  • Yes but I'm trying to avoid showing the API key to the public. That's the only reason why I have to do it this way...wish there is a better way of doing it. – 2myCharlie Mar 23 '16 at 19:29
  • 1
    @Sabbin $form is just fine. the type error happened farther along that line. `.value()` of course isn't a jquery method. – Kevin B Mar 23 '16 at 20:51

2 Answers2

0

Here's an example to do what you describe:

$("#frmComment").submit(function(event) {
    event.preventDefault();

    // Form has been submitted - now show your progress gif, eg:
    // $('body').addClass('in-progress');
    // or maybe:
    // $('.spinner').show();
    // etc - CSS can be whatever you want

    // Cache $form, we'll use that selector more than once
    var $form=$(this);

    // Serialize all input from the form
    var data=$form.serialize();

    // Post it
    $.post(
        "your-proxy-url",
        data,
        function(response) {
            // Success callback.  Remove your progress gif, eg:
            // $('body').removeClass('in-progress');
            console.log(response); // show the proxy response on your console

            // Now hide the form
            $form.fadeOut('slow', function() {
                // And show a result once it's gone
                $(".result").html(response).fadeIn('slow');
            });
        }
    );
});
Don't Panic
  • 13,965
  • 5
  • 32
  • 51
  • Thanks! I'll give that a try. I'm not sure why the downvote...would be nice to give reason. – 2myCharlie Mar 24 '16 at 13:18
  • Okay, there is a slight problem with this implementation. I do not want to leave the current page. I just want to submit only the data in the form to the proxy-page. It seemed that this suggestion would post the form to the proxy-page and then leave page as well. I want the user to remain the same page but only submit the form. – 2myCharlie Mar 24 '16 at 16:15
  • No, it should not do that - event.preventDefault() will stop the form being submitted. Do you still have that in your code? – Don't Panic Mar 24 '16 at 16:43
  • I've just updated my initial post to reflect what I've so far and its current issue. – 2myCharlie Mar 24 '16 at 17:34
  • 1
    @Charlie123 `$("##frmComment##")` is not a valid jQuery selector - just one '#' for an id, with nothing trailing. Check the code I posted - `$("#frmComment")`. Likewise all your uses of `$("##submitResponse")` should have just one #. – Don't Panic Mar 24 '16 at 17:39
  • Thanks! I'm writing javascript inside of ColdFusion cfoutput so sometimes I've overlooked. Okay, so that fixed the redirection...it's progress but it's not removing/hiding the form yet. I'll work on that next. – 2myCharlie Mar 24 '16 at 17:44
  • Try one thing at a time - maybe just `console.log(response)` to verify you're getting something back from your proxy. Then add `$form.hide()`, to verify you can hide the form. Then try fadeOut() to get fancy. Etc. – Don't Panic Mar 24 '16 at 17:49
  • And always watch your console :-) – Don't Panic Mar 24 '16 at 17:50
  • Where in my code do add the console.log(response)? I added right after the data, console.log(response),function(response){} and I got an ReferenceError: response is not defined error in the console. – 2myCharlie Mar 24 '16 at 18:09
  • You won't have a response until the AJAX call has happened and the success callback is fired. I've edited my code to include a console.log(). – Don't Panic Mar 24 '16 at 18:25
  • The console.log(response) didn't show anything and that's because it was erroring out before with this error: "NetworkError: 500 Element PROXYURL is undefined in URL. - https://devbox.mysite.com/customcf/kb/proxyPost-KB.cfm" – 2myCharlie Mar 24 '16 at 18:58
  • Looks like the proxy-page was not processed or not found...I don't know but when type in the url manually, the proxyPost-KB.cfm does show up. – 2myCharlie Mar 24 '16 at 18:59
  • It looks like the jquer post does seemed to send the data to my proxyPost-KB.cfm page but when it gets to that page, it error out with 505. I guess this is something I need to get help from the ColdFusion folks on how to configure my proxy page to respond back to my jquery post. – 2myCharlie Mar 24 '16 at 19:26
  • 500 response is server error, ie misconfigured server or something like that. Check the server logs to find out what is happening. Does the "element PROXYURL" error make any sense in the context of your ColdFusion code? And a 505 response is very odd, or is that a typo? – Don't Panic Mar 24 '16 at 19:38
  • Thanks for the additional help. I removed the cfset PROXYURL and now I got a new error: NetworkError: 500 Complex object types...erted to simple values. – 2myCharlie Mar 24 '16 at 19:47
  • Sounds like trouble in your ColdFusion code - might be easier to temporarily disable the JS and just POST normally to it until that's resolved? The page will refresh and the ColdFusion response will shown in the browser. Just an idea. Good luck! If my answer helped would you consider accepting and/or upvoting? Thanks. – Don't Panic Mar 24 '16 at 21:31
  • How do I send just the name, email, and message? Right now, it sends everything including the recaptcha code which I don't need. – 2myCharlie Mar 25 '16 at 14:59
  • Okay, I got the proxy page to submit but I think there is something wrong with the url that the javascript post to. Is there a way to get the full URL before the jquery post? – 2myCharlie Mar 25 '16 at 15:39
  • Not sure what you mean - you have the URL, in your code it is "/customcf/knowledgeOwl/proxyPost-KB.cfm". You can fully qualify it if you need, eg http://somewhere.com/customcf... – Don't Panic Mar 26 '16 at 15:34
  • The [jQuery docs](http://api.jquery.com/jquery.post/) show examples of how to post individual data. – Don't Panic Mar 27 '16 at 09:42
-1

I think you could use this code inside the $( "#frmComment" ).submit(function( event ) { function:

event.preventDefault();
var data = $('#frmComment').serialize(); //get all the data of form
var url = "yourUrl.php";

 $.ajax({
    type: "POST",
    url: url,
    data: data,
    dataType: "json",
    success: function(data) {
        //var obj = jQuery.parseJSON(data); if the dataType is not specified as json uncomment this
        // do what ever you want with the server response
    },
    error: function() {
        alert('error handing here');
    }
});

The PHP 'yourUrl' will recive the form inputs (you could use var_dump($_POST); to see the structure.

JP. Aulet
  • 4,375
  • 4
  • 26
  • 39