L
L
lolrofl012018-12-14 21:00:58
JavaScript
lolrofl01, 2018-12-14 21:00:58

How to apply to change a variable from an ajax function?

When the button is clicked, an Ajax request is sent to the server. While it is running, being processed, etc., the same function should not be executed again. Those. so that the button becomes disabled at the time of Ajax operation. And when the answer comes - activated again. It seems like a trivial task, but there were difficulties. Here is the code:

data: {
        enable: true
    },


        sendMessage: function () {

            if( this.enable === true ) {
                this.enable = false;

                window.axios.defaults.headers.common['X-CSRF-TOKEN'] = $('meta[name="csrf-token"]').attr('content');

                axios.post('/url', {

                })
                .then(function (res) {
                  
                    this.enable = true;
                })
                .catch(function (error) {
                    console.error(error);
                });

Here is the construction that goes before axios (this.enable = false) - it works. But the one inside axios (this.enable = true) is not. Because of this, the button works 1 time and does not work anymore. How can this be fixed?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
W
WebDev, 2018-12-14
@lolrofl01

The problem is that a function has its own scope and this inside that function is not the same this as above.
Replace

.then(function (res) {
    this.enable = true;
})

on the
.then(res => {
    this.enable = true;
})

S
Sergey Krivosheev, 2018-12-15
@Nemozar

And better use .finally for axios. Otherwise, you will have to write the button unlock twice.
https://developer.mozilla.org/en/docs/Web/JavaScript...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question