Archive

Posts Tagged ‘jquery’

My errors always return to jQuery’s “success” function?

December 4th, 2009

How do I tell my application that the query was unsuccessful when jQuery insists on always running the “success” function when it returns??

When we make an ajax call with jQuery the server’s response is consumed by the “success” function we’ve provided. “success”, in this case, refers to whether the server responded according to the HTTP protocol. “success”, in this case, does not refer to whether the application was happy to do what we were asking for, or not. If the user tried to do something silly don’t expect that putting a function in the “error” callback will deal with it. “error” and “timeout” are only useful if you want to know when the ajax request couldn’t converse with the server at all.

Q: So how do I tell my application if the call was successful or not?

A: Return a JSON response.

For example have your server return:

{'success': false; "message": "Nah. I'm not in the mood", 'id': 292} or
{'success': true; "message": "Okey dokey!", 'id': 292}

If, in your ajax call, you set the “dataType” to “json” jQuery automatically parses the json and gives you a javascript object all ready to go. Man, this was so wonderful, I thought I should blog it.

This little sample throws up a dialog to present ‘data.message’, then uses ‘data.success’ to decide if the action was successful or not. If it was successful we could use data.id for something useful. But in this case I fade out an element identified with the id passed to the original manage function which is somehow still in scope.


function manage(action, id){
    $.ajax({
        type: "POST",
        data: "action=" + action + "&id=" + id,
        url: "/membership/xhr/manage/",
        dataType: "json",
        success: function(data){
            $("<div></div>").html(data.message).dialog();
                modal:true,
                buttons: {
                    "Ok": function(){
                        $(this).dialog("close");
                        if(data.success) $('#membership_'+ id).fadeOut();
                    }
                }
            });
        }
    });
}

I’d give you a working demo, but that would be work ;-)