Success Message display on submit html form - javascript

I am trying to display a success message just above the submit button, but it’s directing me to a form page. Here it is.
I am trying to:
<!-- The form is on the deck.html page -->
<div class="row footer-newsletter justify-content-center">
<div class="col-lg-6">
<form action="forms/subscribe.php" method="post">
<input type="email" name="email" placeholder="Enter your Email"><input type="submit" value="Subscribe">
</form>
</div>
I am getting form inputs on my email, so where am I wrong in the below code?
// Create email headers
$headers = 'From: ' . $email_from . "\r\n" .
'Reply-To: ' . $email_from . "\r\n" .
'X-Mailer: PHP/' . phpversion();
#mail($email_to, $email_subject, $email_message, $headers);
?>
<!-- include your own success HTML here.
So I am getting form details to email, but the success
message below is appearing on /forms/subscribe.php
where actually I am looking to display just above
button
-->
Thank you for contacting us. We will be in touch with you very soon.
<?php
I tried on submit pop up, alert box, but it always took me to the subscribe page and I am looking to display just before the subscribe button.

We need to:
Capture and stop the submit event from continuing
Show the message
After some time (let's say 2 seconds), continue the submission.
Check the code below:
We attach an event listener to the form. When the 'submit' event happens, we want to execute our code. The e variable represents the event. We want to stop the event from doing its normal stuff (in this case, send the user to another page), so we say e.preventDefault().
I created a p element with the message on top of the form. This element is hidden by default, but if we add a class show to it, it appears. So, that's what we do. After preventing the event from continuing, we add this class to the message.
Finally, we use the setTimeout() function to count to 2 seconds (2000 ms) and then execute form.submit(), which sends the user to the subscribe page.
const form = document.querySelector('form');
const thankYouMessage = document.querySelector('#thank-you-message');
form.addEventListener('submit', (e) => {
e.preventDefault();
thankYouMessage.classList.add('show');
setTimeout(() => form.submit(), 2000);
});
#thank-you-message {
display: none;
}
#thank-you-message.show {
display: block;
}
<p id="thank-you-message">
Thank you for contacting us. We will be in touch with you very soon.
</p>
<form action="forms/subscribe.php" method="post">
<input type="email" name="email" placeholder="Enter your Email">
<input type="submit" value="Subscribe">
</form>

Related

PHP form submission alert not working (no ajax)

This is my first question on StackOverflow - thanks in advance for your help!
I have an html form that emails me upon submission. The form submits successfully but I want it to display a submission confirmation message via pop up alert box before reloading the page. Any help is appreciated - though, I'll say now that I don't intend to use AJAX since I am not at all familiar yet. Thanks!
HTML:
<form method="post" action="php/contactForm.php">
<p class="formBox" id="nameBox">Name:</br><input type="text" id="contactName" name="contactName"></p>
<p class="formBox" id="emailBox">Email:</br><input type="email" id="contactEmail" name="contactEmail"></p>
<p>Message:</br><textarea id="contactMessage" name="contactMessage"></textarea></p>
<p><input type="submit" name="submit"></p>
</form>
PHP in "contactForm.php":
<?php
$name = $_POST['contactName'];
$email = $_POST['contactEmail'];
$message = $_POST['contactMessage'];
$body = $name . "\n" . $email . "\n\n" . wordwrap($message);
$alert = "<script>alert('Thank you for reaching out! Someone will be in touch soon.')</script>";
echo $alert;
mail('email#notmyactualemail.com', 'New Message from Website Contact Form!', $body);
header("Location: ../connect.html");
?>
p.s. If it helps to know, I am hosting on GoDaddy.
AJAX works to run code without having to refresh your page. The PHP code you have now will run after the page reloads. Therefore, there is no way without AJAX to send a genuine confirmation message before the page reloads.
You can, however, use the javascript onsubmit property to make a confirmation alert once the form is submitted, but that will not guarantee that the form was indeed submitted without error. Here's an example:
document.getElementById("myForm").onsubmit = function(){
window.alert("This is the confirmation message!\n\nThank you for submitting");
}
<form action="www.example.com" id="myForm" method="POST">
<input type="text">
<input type="submit">
</form>

How to submit() an input with type="search" with Javascript/jQuery?

I'm building a WordPress theme. I've added an optional feature for page transitions. The concept behind it is simple: a user clicks a link, jQuery intercepts that links with event.preventDefault(), jQuery removes a specific class from the body element and after 300ms the link is loaded yet.
Now I have a problem withs forms. The user can add one search form the the header and one (or multiple) in the sidebar/widget areas.
All forms have less or more the same structure (there is some PHP inside):
<form role="search" method="get" class="ambition-search-form header_search override" action="<?php echo esc_url( home_url( '/' ) ); ?>">
<input type="search" class="ambition-search-field header_search override" id="ambition-search-field-input-header_search"
placeholder="<?php echo esc_attr( get_theme_mod( 'ambition_text_searchfield', 'Start typing...' ) ); ?>"
value="" name="s"
title="<?php echo esc_attr( get_theme_mod( 'ambition_title_searchfield', 'Search for pages, articles and documents.' ) ); ?>"
autocomplete="off" />
<input type="submit" class="ambition-search-submit header_search override" value="" />
</form>
The problem with the forms is that the site goes to the search results page when the user hits enter. Hitting enter isn't a link and therefore jquery can't intercept it, like it does with links. To fix this, I've created the following code:
function ambition_submit(e) {
if (e.key === 'Enter') {
console.log('SUBMIT');
event.preventDefault(); //Stop the link from going (by submitting it)
if ($('body').hasClass('ambition-loaded')) { //For safety
$('body').removeClass('ambition-loaded'); //Remove the .ambition-loaded class
if (!event) {
e = window.event;
}
var ambition_target = event.target || e.srcElement;
console.log(ambition_target);
//And set a timeout and move the browser to the url
setTimeout(function() {
ambition_target.submit();
}, 300);
}
}
}
document.querySelectorAll('input').forEach(item => {
item.addEventListener('keypress', ambition_submit);
})
I'll shortly explain it, although it quite speaks for itself.
AddEventlistener when the user types in one of the forms. A function ambition_submit is called. The function checkes whether the user hit 'enter'. If yes, we use preventDefault. The class ambition-loaded is removed from the body. I store the element on which the event occurred in a variable. (It is logged to the console.) I set a timeout of 300ms and after that the page should be redirected.
In the above code, ambition_target.submit(); doesn't work (.click() doesn't work either).
How do I submit the input field?
(Or, how do I delay the submitting of the form for 300ms and in meantime execute a function which removes the class?)
Many thanks in advance!
The input tag is a child element of the form tag. The .submit() doesn't work on input tags, as that is not a form as whole. Selecting the parent form tag and submitting that instead did it.
Thanks to Andre Nuechter.

PHP Form Submit (save data into a text file) not working

So I do have a form on my web page and I would like to save user's input (email in my case) each time the Submit button is clicked.
HTML:
<form id="email-form" method="post">
<div class="form-group">
<input type="email" class="form-control" placeholder="ex: john#gmail.com" name="email" required>
</div>
<div class="form-group">
<input type="submit" class="cta animated-cta" name="submit" value="Continue">
</div>
</form>
PHP:
<?php
if(isset($_POST['submit'])) {
$email = $_POST['email'];
$file = fopen('list.txt', 'a');
fwrite($file, $email);
fclose($file);
}
?>
The problem is that nothing happens, while the code seems to be correct.
Things I've tried: Created myself the list.txt file (thought it doesn't get created automatically) | Put the script on my host to see if there's any difference (I coded it locally) | Added a PHP redirect to see if the code is executed once I click the button but isn't the case.
P.S: I do have a 'event.preventDefault();' in my javascript file which is executed once the Submit button is clicked (because I don't want the page to refresh once I click). Hovewer I've removed it but nothing changed.
Thank you in advance!

2 in 1: modify php value in runtime, inside echo

I`ll try to explain the best that I can.
I don't know anything about PHP, and very little about js, so, forgive me if this question is stupid.
I'm trying to load a PHP function inside an echo.
this is the function i want to call
function SuccessDialog(){
if(isset($_POST['mailsent']))
{
$to = 'mymail#hotmail.it';
$subject = 'test2';
$message = 'hello';
$headers = 'From: webmaster#example.com' . "\r\n" .
'Reply-To: webmaster#example.com' . "\r\n" .
'X-Mailer: PHP/' . phpversion();
mail($to, $subject, $message, $headers);
}
}
I need to call this when an upload is successfull and an "echo" opens a dialog, in which there should be a "send email button" (at the moment I don't care about the mail is working or not, since it is).
The script for said button is this
<form action="" method="post">
<input type="submit" value="Send email" />
<input type="hidden" name="mailsent" value="1" />
</form>
(actually I can't understand why it should be inside a form, but it's working)
And so, the first part of the question. Since this code is working if used with a button outside the echo, how can I manage to make it work with this particular button?
And here for the second question.
Since the email address should be an input from the user, I should be able to modify the "$to" in runtime, still being inside the echo. Can I do that, or since php is server side I'm stuck or I got it wrong from the beginning?
Thanks
Well, if I got it right, you have to add
<input type="text" name="to">
to the form, and you wold be able to get the value in $_POST['to'] in php. Remember to sanitize user input!
edit
To make user unable to submit the form without adding an email address add required attribute to the field.
You can use type="email" to make browser (a new one) validate the input.

Using HTML 5 / Javascript template to send contact e-mail form

I recently created a simple site for a friend's business using an HTML 5 template. It contained some cutesy Javascript elements too. The website URL is www.michianamemories.com
One of the elements is a Contact Form at the bottom of the page. It looks like the "Send Message" button is coded to do absolutely nothing. How simple is it to have this form forward the user-entered values (ie: their name, e-mail, and their message) to a dedicated e-mail inbox?
If it's not that simple, what other options are available to make the form functional but also integrated with the site's general theme?
I'm assuming the answer is very simple, but I'm a novice at HTML 5 and am totally clueless about Javascript. Your help is appreciated in advance.
HTML doesn't allow you to submit a form to an email.
You could use mailto but it's not the friendliest piece of functionality. It will open up Outlook and dump the form data into the email content. Has a lot of issues though.
More info on mailto
My recommendation is to use a "form mail script". This is only done on server side though so you'll need to have a web server. You'll need to google and read up on them.
Reference about form submit options
It's not possible in pure Javascript. Sending email requires server-side processing.
There are several websites that will let you generate simple email forms, check out: http://www.google.com/search?hl=en&safe=off&q=email+form+generator&aq=5&aqi=g10&aql=&oq=email+form
In my opinion the best thing you can do is to create a simple Back-End App in PHP.
Create file mail.php in your root directory.
In your HTML form tag you need to add the action attribute with the path to mail.php file and the method attribute, so that the form knows which HTTP Request Method use to send the data <form action="mail.php" method ="post">. This will add the action to trigger for the 'Send Message' button, that you said is not working.
This happens because now the button knows what to do if you click it. It takes all of your data from the form input fields and send them to the mail.php file. This file needs to fetch them and validate them. (You should at least create the validation for the required fields in your form, to check if they're not null. You can make some extra validations in your build-in html attributes or with some help of the JavaScript)
The most important thing now, is to create the Mail function in your mail.php. Here is all the documentation you need to do this: PHP Mail Documentation.
Here is the code (your site is not working so I'm just improvising with the input fields):
HTML:
<form action="mail.php" method="post">
<label for="name-field">Name:</label>
<input id="name-field" name="name" type="text" required>
<label for="surname-field">Surname:</label>
<input id="surname-field" name="surname" type="text" required>
<label for="message-field">Message:</label>
<textarea id="message-field" name="message" required></textarea>
<label for="mail-field">Your e-mail:</label>
<input id="mail-field" name="mail" type="mail" required>
<button type="submit">Send Message</button>
</form>
PHP:
// Validating if everything is filled
if(isset($_POST['name']) && isset($_POST['surname']) && isset($_POST['message']) && isset($_POST['mail'])
{
$to = "example#mysite.com";
$subject = "Automatically generated messege from" . $_POST['name'] . ' ' . $_POST['surname'];
$body = $_POST['message'];
$headers = 'To: ' . $to . "\r\n";
$headers .= 'From: ' . $_POST['mail'];
// Send mail function
if(mail($to, $subject, $body, $headers))
{
echo 'Mail sent successfuly!';
} else {
echo 'Error occurred while sending the message';
}
}
As mentioned in the other answers, you can't use HTML5 to send e-mail. This needs to be done on your server.
One easy and free solution is to use Google Apps Script though. You can publish your Apps Script as a Web App and have a doPost method like this:
function doPost(e){
var email = e.parameter.email;
var subject = 'E-mail from website';
var message = e.parameter.message;
MailApp.sendEmail(emailAddress, subject, message);
return ContentService.createTextOutput('E-mail sent!');
}
And in your HTML, you would have a form like this:
<form action="url to your deployed app script" method="post">
<input type="email" name="email"></input>
<textarea name="message"></textarea>
<input type="submit" value="Submit"></input>
</form>
The URL to put in the action attribute will be shown when you deploy your Apps Script as a Web App:

Categories