Antonio
Antonio

Reputation: 59

Change cursor to wait before an Ajax petition is sent

I have the following JavaScript function, which is executed when a button is clicked:

function calculate(resource) {
    document.getElementById('loading-label').innerHTML = 'Calculating...';
    $.ajax({
        url: resource,
        type: 'GET',
        async: false,
        headers: {
            'Content-Type': 'application/json'
        },
        beforeSend: function () {
            document.body.style.cursor('wait');
        },
        complete: function () {
            document.body.style.cursor('default');
        }
    }).done(function (data, textStatus, jqXHR) {
        if (data == true) {
            document.getElementById('loading-label').innerHTML = 'Done!';
            document.getElementById('loading-label').style.color = 'green';
        } else {
            document.getElementById('loading-label').innerHTML = 'Error!';
            document.getElementById('loading-label').style.color = 'red';
        }
    });
}

But it doesn't work as I want. Maybe because I'm not using beforeSend and complete callbacks properly.

As it can be seen, when the button is clicked, a label changes its content and I would like to change the cursor to waiting until the synchronous call is finished (and then return to default). How could I do that?

Upvotes: 0

Views: 134

Answers (1)

Quentin
Quentin

Reputation: 943220

You can't when you make a non-async request.

Aside from your trivial error (you need to assign new values to cursor with =, it isn't a function).

Synchronous requests block the event loop (which is why they are deprecated). Since the event loop is blocked, the browser doesn't perform a repaint, and the cursor doesn't change.

Write asynchronous code instead.

function calculate(resource) {
    document.getElementById('loading-label').innerHTML = 'Calculating...';
    document.body.style.cursor = 'wait';
    $.ajax({
        url: resource,
    }).done(function (data, textStatus, jqXHR) {
        if (data == true) {
            document.getElementById('loading-label').innerHTML = 'Done!';
            document.getElementById('loading-label').style.color = 'green';
            document.body.style.cursor = 'default';
        } else {
            document.getElementById('loading-label').innerHTML = 'Error!';
            document.getElementById('loading-label').style.color = 'red';
            document.body.style.cursor = 'default';
        }
    });
}

Upvotes: 1

Related Questions