Search code examples
jquerycoldfusion-11

Ajax response undefined on .keyup operation


I have created a input formfield for a user to type in a captcha that they see from an image created by Coldfusion's cfimage tag and stored in a session var. When the user types in the captcha into the input formfield, jQuery calls a Coldfusion CFC to check if the captcha the user entered matches the session var. If the user matches the captcha, the submit button is shown. All seems to working fine until the response comes back. Here is my code.

HTML

<input type="text" id="mailform-input-captcha" name="captcha" placeholder="Type in Captcha *" data-constraints="@NotEmpty"/>

jQuery

    $(document).ready(function() {
    $('#mailform-input-captcha').keyup(function(){
        var captcha = $('#mailform-input-captcha').val();
        $.ajax({
            type: "POST",
            url: "cfc/handy.cfc?method=chk_captcha&returnformat=json",
            datatype: "json", 
            data: {
                captcha: captcha
            },
            cache: false,
            success:function(data) {
                if(data && data.length) {   // DO SOMETHING
                    $.each(data, function(i, val) {
                        console.log(val);
                        console.log(data[i].status);
                        // *** SUCCESS ***
                        if(status == "SUCCESS") {   // DO SOMETHING 
                            $('.btn').show();
                            alert(status);
                        // *** FAIL ***
                        } else if(status == "FAIL"){ // DO SOMETHING
                            $('.btn').hide();
                        }
                    });
                }
            }
        });
    });

If I type letters in the input formfield, the response comes back as an array of structures from the CFC. Here is an example of the response.

Response

[{"STATUS":"FAIL"}]

When I look in the chrome debugger I see the following:

  1. console.log(val); logs each individual character in the array instead of each structure.
  2. console.log(data[i].status); logs as "undefined".

The site is utilizing jQuery 1.7.1 I have tried a newer version of jQuery and did not see a change. This script has worked on other sites just fine. Thank you for any input you may have.


Solution

  • You have a typo in datatype which should be dataType

    Also a good idea to return appropriate Content Type header. Since dataType is not set and header isn't application/json it seems to be treating the response as text

    Also note that javascript is case sensitive so you need to check data[i].STATUS or change the output