Skip to content
Advertisement

Submitting an HTML form to a PHP file with JS validation

I’m sending data via an HTML form to a PHP file for it to be inserted into a DB with SQL script, The same form is validated with JavaScript functions.

Each of the two works as expected separately, but when used together – <form method="POST" action="myPHPFile.php" onsubmit="validationFunc(event)"> – only the validation function works, and the page doesn’t get redirected to the PHP file.

When removing the JS (leaving only <form method="POST" action="myPHPFile.php">) – the data from the form is submitted properly and the page is redirected to the PHP file as expected.

I need to have some JS function to stop if the input is invalid, and another to continue and send the input data to the PHP file if it’s valid.

Example code:

JavaScript
JavaScript

I’d be happy for some help with:

  1. How to redirect the input data to the PHP file (without removing the JS validation)
  2. How to implement the JS functions to send the data to the PHP/cancel.

Thank you!

Advertisement

Answer

Instead of the button being a submit button just have it be a regular button that calls your javascript function. Then, do all of your validation in the function… at the end, you can have a conditional statement which checks if all conditions are met. If they are, then submit the form. (Assign an id to your form)
Check out this pseudo-code let me know if this works or you need further instruction

JavaScript
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement