Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

$.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?

like image 323
Fred Collins Avatar asked Mar 06 '26 07:03

Fred Collins


1 Answers

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.

like image 178
Kai Qing Avatar answered Mar 07 '26 20:03

Kai Qing



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!