Search code examples
javascriptjqueryajaxjquery-callback

$.post() callback method suggestion


I always used something like this:

$("a.button").click(function() {
    data = ...;
    url = ...;
    $.post(url, data, function() {
        $(this).toggleClass('active');
    });
});

The problem is when an user has a slow connection and clicks on that button, it doesn't seems to do anything, because the button will change the own status (adding the active class) once the request is complete. Of course I can "fix" this behavior by adding a spinner while the request is loading.

Now check out this one:

$("a.button").click(function() {
    $(this).toggleClass('active');
    data = ...;
    url = ...;
    $.post(url, data, function() {
        // if request is successful do nothing
        // else, if there's an error: $(this).toggleClass('active)
    });
});

In other words, I change the button status instantly when the button is pressed and after this, I check for success/error. Is this a good way? What you think about? Are there other ways?


Solution

  • This is more of a UI question than code. Personally I prefer to show the spinner in cases where it could be confusing if there is no response. Since I don't know what class you're toggling and what effect it has on the element, I wouldn't know if toggling before success would be confusing at all.

    One way or another, everyone alive knows the loading spinner. It's probably safe to go with that.