I have this html form that interacts with a MySQL
database created in XAMPP
. I'd like to validate it in such a way that once controlled the first two boxes(Name and Email areas) are filled it sends the message to the database using a php script I wrote.
I have written the javascript code to validate the form, but it works even if the first two fields are not filled, so it's wrong in some way.
Here are the files(html, javascript and php):
html form
<html>
<header>
<script type="text/javascript" src="javascript/validateForm.js"></script>
<?php include("connectivity.php"); ?>
</header>
<body>
<form name="contactForm" id="contactForm" method="post" action="connectivity.php">
<div class="form_settings">
<p><span>Name and Surname</span>
<input type="text" name="nome" id="nome" />
</p>
<p><span>Email</span>
<input type="text" name="email" id="email" />
</p>
<p><span>Message</span>
<textarea rows="8" cols="50" name="messaggio" id="messaggio"></textarea>
</p>
<p style="padding-top: 15px"><span> </span>
<input class="submit" type="submit" name="invia" value="Invia" onclick="checkForm()" />
</p>
</div>
</form>
</body>
</html>
javascript file to validate(it is wrong in some way)
function exists(input) {
atLeastOneChar = false;
if (input) {
for (i = 0; i < input.length; i++) {
if (input.charAt(i) != " ") {
atLeastOneChar = true;
break;
}
}
}
return atLeastOneChar;
}
function checkForm() {
mes = "";
if (!exists(document.contactForm.nome.value))
mes = mes + "Missing name
";
if (!exists(document.contactForm.email.value))
mes = mes + "Missing email
";
if (mes != "")
alert(mes);
if (mes == "") {
alert("Ok, correct!
The form should now be sent to " +
"the server!");
}
}
php file to interact with database
<?php
$db = new PDO('mysql:host=localhost;dbname=myprojectdb;charset=utf8',
'root',
'',
array(PDO::ATTR_EMULATE_PREPARES => false,
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION));
?>
<?php
if (isset($_POST['nome'])) {
$nome = $_POST['nome'];
$email = $_POST['email'];
$messaggio = $_POST['messaggio'];
$stmt = $db->prepare("INSERT INTO `contatti` (contattoNome,contattoEmail,messaggio)
VALUES (:nome, :email, :messaggio)");
$stmt->bindParam(':nome', $nome);
$stmt->bindParam(':email', $email);
$stmt->bindParam(':messaggio', $messaggio);
$stmt->execute();
echo 'email inviata correttamente';
}
?>
How can I solve this problem?