Using javascript and php together
Posted
by EmmyS
on Stack Overflow
See other posts from Stack Overflow
or by EmmyS
Published on 2010-05-17T22:32:45Z
Indexed on
2010/05/17
22:40 UTC
Read the original article
Hit count: 272
JavaScript
|php
I have a PHP form that needs some very simple validation on submit. I'd rather do the validation client-side, as there's quite a bit of server-side validation that happens to deal with writing form values to a database. So I just want to call a javascript function onsubmit to compare values in two password fields. This is what I've got:
function validate(form){
var password = form.password.value;
var password2 = form.password2.value;
alert("password:"+password+" password2:" + password2);
if (password != password2) {
alert("not equal");
document.getElementByID("passwordError").style.display="inline";
return false;
}
alert("equal");
return true;
}
The idea being that a default-hidden div containing an error message would be displayed if the two passwords don't match. The alerts are just to display the values of password and password2, and then again to indicate whether they match or not (will not be used in production code).
I'm using an input type=submit button, and calling the function in the form tag:
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post" onsubmit="return validate(this);">
Everything is alerting as expected when entering non-matching values. I would have hoped (and assumed, based on past use) that if the function returned false, the actual submit would not occur. And yet, it is. I'm testing by entering non-matching values in the password fields, and the alerts clearly show me the values and the not equal result, but the actual form action is still occurring and it's trying to write to my database.
I'm pretty new at PHP; is there something about it that will not let me combine with javascript this way? Would it be better to use an input type=button and include submit() in the function itself if it returns true?
© Stack Overflow or respective owner