I understand that they are different, and they each have their own special things that they do Client and Server side. But let's say you are validating a form. You use JavaScript to validate the form, then if there are no errors, you run PHP to insert a record into database. How would you do this? Is there any way to run PHP in JavaScript or call on a PHP method together?
-
2Have you tried it? – Funk Forty Niner Nov 01 '16 at 15:03
-
Can we use the same sentence in both the title and the content of a question on StackOverflow? – nozzleman Nov 01 '16 at 15:07
-
Yes, you could. Add code too broad as is. – chris85 Nov 01 '16 at 15:09
-
2Possible duplicate of [form validation with javascript vs php](http://stackoverflow.com/questions/1726617/form-validation-with-javascript-vs-php) – Funk Forty Niner Nov 01 '16 at 15:10
1 Answers
You can use both JavaScript and PHP validation together (in fact, you should). Probably the easiest way to do this is add a hidden submit button on your page. The visible submit button should be of type button
and should trigger your JavaScript validation. Then, if the input passes your validation rules, trigger a click on the hidden button to submit the form to the server.
It is worth noting that if you do follow this route, you must also remember to catch submissions that are done using the Enter
key (since this key press automatically triggers form submissions) and pass them through your own custom function.
Of course you could also disable the submit button entirely until the form passes the JavaScript validation. With this method, you can check each field as the value within it changes and then only enable the submit button when the form is fully valid.
Without examples, it is difficult to come up with a solution to your specific use case.

- 607
- 1
- 10
- 28