I'm trying to create that simple email subscription form for my website. Every time an email is added, I'd like the input box to confirm that the email was added. It seems like something very simple but I can't find the way to echo an answer in the input box dynamically. I know how to change the input value with Javascript but it doesn't seem to work once included in the PHP.
Edit: I'm not very familiar with PHP. I know I'm not supposed to include Javascript in my function, it is just an example of what I want to achieve.
Is there an easier way to do that?
Thanks!
<div id="email_form">
<form action="" method="post">
<input name="email" class="email" type="text" placeholder="Subscribe" id="emailinput"><button type="submit" name="SubmitButton" class="btn_email"><b>></b></button>
</form>
</div>
<?php
if(isset($_POST['SubmitButton'])){ //check if form was submitted
$to = "myemail@email.com";
$from = "no-reply@email.com";
$headers = "From: " . $from . "
";
$subject = "New subscription";
$body = "New user subscription: " . $_POST['email'];
if( filter_var($_POST['email'], FILTER_VALIDATE_EMAIL) )
{
if (mail($to, $subject, $body, $headers, "-f " . $from))
{
echo '<script type="text/javascript">';
echo 'var elem = document.getElementById("emailinput");';
echo 'elem.value = "Submited!";';
echo '</script>';
}
else
{
echo 'It works but There was a problem with your e-mail (' . $_POST['email'] . ')';
}
}
else
{
echo 'It kinda works but there was a problem with your e-mail (' . $_POST['email'] . ')';
}
}
?>
Do your processing of the submission before you echo the form. Then if the email was processed successfully, when you echo the input box, echo your input with the attribute value="Success!"
Thanks all, putting the PHP first and echoing the value worked. I'm actually using the placeholder instead of the value so it's not editable.
First time asking a question on Stackoverflow and definitely not disappointed by that great community.
Here is my final code for reference:
<?php
if ( isset($_POST['SubmitButton']) ) {
$to = "myemail@email.com";
$from = "no-reply@email.com";
$headers = "From: " . $from . "
";
$subject = "New subscription";
$body = "New user subscription: " . $_POST['email'];
$message = "";
$value = "";
if( filter_var($_POST['email'], FILTER_VALIDATE_EMAIL) ) {
if (mail($to, $subject, $body, $headers, "-f " . $from)) {
$value = "Submited!";
} else {
$value = "Invalid Email";
}
} else {
$value = "Invalid Email";
}
}
?>
<div id="email_form">
<form action="" method="post">
<input name="email" class="email" type="text" id="emailinput" placeholder="<?php echo $value; ?>" />
<button type="submit" name="SubmitButton" class="btn_email">
<b>></b>
</button>
</form>
</div>