I made a simple contact form and I am trying to figure out how to change the html elements on the page to create a confirmation for when the e-mail is sent. As of now, it just reloads the page if an e-mail is sent. I would also like error messages to appear beside the input label as an html element if the name section is blank or e-mail entered is not valid.
This is the code that I have currently:
HTML:
<div id="contact-content" class="format-div">
<form id="contact-form" action="/contact-form.php" method="post">
<label for="contact-name">Name</label>
<input type="text" id="contact-name" name="nameIn" placeholder="Enter
your name!">
<label for="email-address">E-mail</label>
<input type="text" id="email-address" name="emailIn" placeholder="Enter your e-mail address!">
<label for="contact-message">Message</label>
<textarea id="contact-message" name="messageIn" placeholder="All this space to fill with words..."
style="height:200px"></textarea>
<button type="submit" name="submit-mail"><i class="far fa-paper-plane"></i></button>
</form>
</div>
PHP:
if (isset($_POST['submit-mail'])) {
$name = $_POST['nameIn'];
$address = $_POST['emailIn'];
$message = $_POST['messageIn'];
$error = "";
if($name == '') $error .= 'Please fill in your name';
if (!filter_var($address, FILTER_VALIDATE_EMAIL)) $error .= 'The e-mail is invalid';
$mailTo = "myemail@mysite.come";
$subject = "FROM WEBSITE: ".$name;
$header = "Mail from: ".$name.", ".$address."
";
mail($mailTo, $subject, $message, $header);
header("Location: index.html?mailsent");
}
Inside a HTML tag you can put this: <php if (isset($_POST['submit-mail'])) { echo $error; } ?>
so if theres an error it will show inside the HTML tag
Somewhere in your html page basically at the top perhaps you should catch the GET variable, if it was set. also you can display error similarly.
if(isset($_GET['mailsent'])){echo "Email Sent";} else if(isset($error)){echo $error;}
Also if index.html is not the page that has the form code then it will not have access to the error variable so.
change header("Location: index.html?mailsent");
to header("Location: index.html?error=".$error."&mailsent=");
and because your html page will need to parse php ideally it should be a php page i.e index.php
header("Location: index.php?error=".$error."&mailsent=");
of course rename the index.html page to index.php. if u do not want to do it then take the JavaScript approach.