Tuesday, April 19, 2011

jQuery ajax success callback not triggered

Recently I started to learn jQuery due to its popularity (jQuery IN ACTION has come to 2nd edition, and many companies/projects are using jQuery). One typical use of jQuery is for ajax call. I wrote a very simple testing code (see below) to check how it works but got a problem - the success callback function is not triggered.

I tried both $.getJSON() and $.ajax() methods but no luck. After further check, I found in the server side returned JSON string, there is a backslash (which is supposed to escape single quote, but it was wrongly composed because http://www.json.org/doesn't say we need escape single quote). Due to that, something like {"name": "hj", "description": "hj\'s blog"} will not trigger success callback. However, it will trigger error and complete callback.

There is an online tool called http://www.jsonlint.com/ where we can validate JSON string. For above mal-format string, we will get below error
syntax error, unexpected TINVALID at line 3
Parsing failed

The fix is easy - remove the extra invalid escape backslash, so the valid JSON string is:
{
    "name": "hj",
    "description": "hj's blog"
}

Here is the code snippet I wrote (googled) for test.

    <script type="text/javascript">
        $(document).ready(function() {
            $("#login_button").click(function() {
                var unameval = $("#username").val();
                var pwordval = $("#password").val();

                var thedata = "email="+unameval+"&pass="+pwordval;
                alert(thedata);

                //do ajax call -> method 1       
                /*
                $.getJSON("http://localhost:8080/api/login", thedata,
                       function(json){
                           alert("yes");
                           alert(json.user.email);                          
                    });
                */
                                                               
                //do ajax call -> method 2
                $.ajax({
                    type: "POST",
                    url: "http://localhost:8080/api/login",
                    data: thedata,
                    //crossDomain:true,
                    dataType:"json",
                    success: function(msg){
                        alert("success event");
                        $("#status").html(msg);
                        alert(msg.user.email);
                    },
                    error: function() { alert("error"); }
                    /*
                    complete: function(msg) {
                        alert("complete event");
                        alert(msg);
                    }
                    */
                });

                return false;
            });
        });
    </script>

PS: firebug trims backslash and displays the well-formed JSON in its JSON tab.

No comments:

Post a Comment