Possible Duplicate:
[PHP/JavaScript]: Call PHP file through JavaScript code with argument
Ok so I use Javascript to validate my HTML forms input values, but I use PHP to write these values into a database.
Is it possible to send my form to the PHP file through Javascript?
This is how I did it without the Javascript, it’s supposed to send the form when you click the submit button to the PHP file.
This is my original form:
<form name="filler" method="post" action="display.php">
//form stuff
</form>
Here’s as far as I’ve gotten. Although I can’t see anything that is supposed to error nothing happens when it is time to validate my form with Javascript, it merely goes to the PHP immediately no matter what I type in. What is still wrong with it?
<!DOCTYPE HTML>
<html>
<head>
<script type="text/javascript">
function required1(n,s,u,e,d,p,cp,g)
{
if (n.value.length > 0 && s.value.length > 0 && u.value.length > 0 && e.value.length > 0 && d.value.length > 0 && p.value.length > 0 && cp.value.length > 0 && g.value.length > 0)
{
return true;
{
else
{
alert('You have not filled in all the fields');
return false;
}
}
function required2(e)
{
if(e.indexOf('.') != -1 && e.indexOf('@') != -1)
{
return true;
}
else
{
alert('Not a valid email address');
return false;
}
}
function required3(d)
{
if(/^\d{2}\/\d{2}\/\d{4}$/.test(d))
{
return true;
}
else
{
alert('Date is not in the right format (DD/MM/YYY)');
return false;
}
}
</script>
</head>
<body>
<form name="filler" method="post" action="display.php" onsubmit="return required1(document.filler.name,document.filler.surname,document.filler.username,document.filler.email,document.filler.dob,document.filler.password,document.filler.confirm_password,document.filler.gender) && required2(document.filler.email) && required3(document.filler.dob) ">
<input name="name" placeholder="Name..."/>
<input name="surname" placeholder="Surname..."/>
<input name="username" placeholder="Username..."/>
<input name="email" placeholder="Email address..."/>
<input name="dob" placeholder="YYYY/MM/DD"/>
<input name="password" placeholder="Password" type="password"/>
<input name="confirm_password" placeholder="Password" type="password"/>
<input name="gender" placeholder="Gender..."/>
<input type="submit" value="Submit"/>
</form>
</body>
</html>
There’s no reason to use AJAX for this. The most elegant and easiest way is to use the HTML form tag’s
onsubmitevent:This will call the JS function
validateFormbefore submitting the form. If the functionvalidateFormreturnsfalse, the form will not be submitted. Otherwise it will be submitted to your PHP file as usual.EDIT:
Make sure you’re validating this input in your PHP as well, since Javascript can easily be disabled.