Using Node.js, I have a form that uses twilio to send an SMS. Everything works fine testing it with my phone.
However, I would like to have an animation play (in my front-end JS file) if the form submit encounters an error in the back-end. Specifically, the twilio API has a callback that takes an error as an argument with the sendMessage function. So I'm not talking about validation errors, but actual errors with twilio or the connection.
So how do I have an event listener in my front-end js files to listen for when there is an error in the callback function of submitting the form (in the back-end) so I can play an animation expressing something went wrong.
Or should I not use event listeners and do it another way?
Any help appreciated. Please respond. Thank you!
No you cannot add an event listener in the front-end for an error in the back end. That is not possible.
If using a HTML form without AJAX:
Now you are using the default HTML form and using the action and method attributes to submit the form data. Then the process will be similar to what you do with error handling. You submit the data then proceed with your interaction with Twillo API. If something fails you redirect the user to the form page with the error message/error animation.
If using AJAX:
Now as you are using AJAX you must have the ability to handle the response you get from the server.
In this process when the user submits data the back-end proceeds with the interaction with Twillo API. If something fails you send back an 500 Internal Server Error with the proper error message.
In the AJAX request callback you check the response code and error message. If something is wrong you can now play the error animation/let the user know about what happened.
Resources:
https://nodejs.org/api/synopsis.html
Check the example in this link. It is shown how to set statuscode for the response.