This might be a broad answer to give but i\'l try to shorten it up. What i am trying to do is use a form to get some information from the user and \"validate the form\" using Ja
If you want to validate data before submitting, you need to listen for the submit
event of the form. Inside the listener you can retrieve the data from inputs, validate it, set appropriate warnings, if necessary and so on. If the validation failed, you can prevent submitting returning false
from the listener.
First off, you want to validate data in a form using JavaScipt. That is simple you could run all of your checks and validate, but the problem that comes next is what do you want your site to do. You want the data to reflect on the page but you haven't mentioned to us the goal of your website. See if I had something simple and wanted to run checks on a form and output somewhere else on the website it is as simple as:
Same Page Validation
- Grabbing data from form
- In the form submit code run validate checks on your inputs either using functions or if statements. (google each for best practices).
- What if a validation fails? you have to handle that by appending notices to the html to show the user that an error validating has occurred.
- Once your form is finished validating, you have to e.preventDefault() which will prevent site from loading.
- If the validation worked, grabbed the values of the form input and append them to a html element so you could output them.
Ok but as you can see there are 100's of ways for you to do this even without having a form go through the submission process. Why not just run a function on a onClick that runs the same validation and returns you the data then you could append that to the html.
But on another note, the reason why your data gets deleted is because the form is trying to do something with the data and when the page refreshes nothing happened with it so everything is lost. The proper way to do this is you were trying to build an application would go like this:
Normal Form Submission
- Once input from user is entered and submit button clicked. Run validation, if any errors prevent form from submitting but if no errors continue
- Run back end validation on your lets say php file. Run the same validation you did in JS but in PHP or your preferred back end language. If there are any errors you need to study up on displaying php errors on form submission to the user.
- If everything works you could store the user information in a database, then query for a specific user.
- If you want same page no reloading information showing you need to study on ajax with php. It's good practice and really cool once you have it working.
- in order to show the user information you also have to think about when grabbing data from backend. if you are going to show the user that was just entered then you can grab last user of the list.
There are so many ways to go about it and to put the code for all of it to work will take way more time but I hope I gave you an idea of what you could do.
Without looking at your code too closely, here is the requested "big picture" overview of what happens when a form is submitted, and how to validate a form.
First, the form and what happens when it is submitted.
When you click the submit button, your form data will be sent to the file specified on the form tag - in your case, "/action_page.php". What arrives there are a number of variables (aka "key-value pairs" - but they are variables with a name and a value). Note that the "variable name" is what is specified in the name=
attribute of the (for e.g.) input field, and the "variable contents" is whatever is typed into the (for e.g.) input field.
Your back-end PHP file will need to create proper PHP $variables for each of these items, using either the $_POST or $_GET command, depending what method you used in the "method=" attribute of the form tag. As an example, your form has a textarea element called name=comment
. On the PHP side, you can write:
$cmt = $_GET['comment'];
and presto! you have the user's comment in a PHP variable $cmt.
You can do the validation at this stage, or you can validate the code in javascript before the file is even submitted (note that javascript can intercept the form submit process and stop it, or continue it.
Then, your PHP file can either send the user back to the same page (in which case, you need a <? php>
section at the top to handle that), or on to another page entirely.
IMPORTANT NOTES:
Important: From your specified action=
location of the PHP file, you might have some trouble because you started it with a slash. That sends the OS back to the root of the file system to find your file, and is probably not what you want. For now, put the "action_page.php"
file in the same location as your index.php
file and drop the leading slash.
At the beginning, do not use the same PHP file to receive the form that you are using to display the form to the user. Same goes for AJAX (getting to that). Do things at first so it is easy for you to understand the process, then make it cooler.
You can validate the user data either in JS before you submit, or in PHP after submitting. However, javascript can be read, debugged, and even changed in the DevTools (F12) console - so other than super basic stuff like "Was the field left blank", do not do your important validation in javascript.
NEVER TRUST USER DATA. Some users are hackers and they can OWN you if you do not sanitize the data they enter. Research sanitizing user data and this also will get you started on the understanding part.
When you submit a form, the screen will refresh. So what about those websites where you fill-in a form, submit, and nothing refreshes but the changes are updated on the existing page. That is done through AJAX.
AJAX is really very simple - almost simpler than a form. The cardinal rule of getting started with AJAX is the same as my note above: have a different back-end PHP file than the one the user is presently on.
Frankly, these days, we don't really use forms very much anymore. Almost everything we used to do with forms we now do with AJAX - and It Is Easy!
So how does AJAX work? Essentially, javascript sends the form data (see below examples!) to the specified PHP file, which processes the data and echo
's back a response. You receive that response, break it up into variables, and change the page accordingly. See references below for more.
NOTE: If you take ten minutes to try the examples in the referenced posts below, you will save yourself HOURS of head scratching. Just reproduce the examples on your own server and play with them a bit.
REFERENCES:
How a form works
HTML Forms vs Ajax
Simple overview of AJAX
Simple login system with ajax
You need to use event.preventDefault()
to prevent the default action of the form, which is submitting.
Change
document.getElementById('submit').addEventListener('click',
function(e){
document.querySelector('.feedback-background').style.display='none';
document.querySelector('.popup').style.display='flex';
}
To
document.getElementById('submit').addEventListener('click',
function(e){
document.querySelector('.feedback-background').style.display='none';
document.querySelector('.popup').style.display='flex';
e.preventDefault();
}
However, preventing the form from submitting will prevent the data from the form from being sent to the server to be processed and saved in the database. To be able to process data sent to the server, you will need to use some server-side programming language and you will need to set the form's action
attribute; Javascript is not sufficient for this task.