Home > OS >  how to reset form data after successfull axios post request
how to reset form data after successfull axios post request

Time:04-05

I have modalform component made using Alpine js and axios for POST request. But I cannot understand few things:

  1. How to reset form data after succesfull POST request. I see error in console TypeError: this.resetFields is not a function

  2. How to get errors to show them for the user if POST request is failed due to validation errors with 422 status code. I want to bind errors.message to AlpineJs variable errors and then show it on the webpage using <p x-text="errors" ></p>, but this.errors = error.message; seems not working, because in AlpineJS devtools in Chrome errors variable doesn't change.

        function modalform() {
            return {
                mailTooltip: false,
                instagramTooltip: false,
                openModal: false,

                formData: {
                  name: '',
                  phone: '',
                  email: '',
                  address: '',
                  message: '',
                  _token: '{{ csrf_token() }}'
                },

                message: '',
                errors: '',
                loading: false,
                sent: false,
                buttonLabel: 'Send',

                resetFields() {
                        this.formData.name = '',
                        this.formData.phone = '',
                        this.formData.email = '',
                        this.formData.address = '',
                        this.formData.message = ''
                },
                
                submitData() {
                    this.buttonLabel = 'Sending...';
                    this.loading = true;
                    this.message = '';

                    axios.post('/modalform', this.formData)
                    .then(function (response) {
                        console.log(response);
                        this.resetFields();
                        this.message = response.data.name;
                    })
                    .catch(function (error) {
                        console.log(error);
                        this.errors = error.message;
                    });

                },
            }
        }
```

CodePudding user response:

You have a scoping issue. If you use the old function(response){...} style, then this refers to the object it was called on (axios). However is you replace it with the arrow function, then this will refer to the first non-arrow function object, in this case: the Alpine.js component.

axios.post('/modalform', this.formData)
.then((response) => {
    console.log(response);
    this.resetFields();
    this.message = response.data.name;
})
.catch((error) => {
    console.log(error);
    this.errors = error.message;
});
  • Related