Below are links to Github repository with complete code and also link to live demo on Codepen where you can see the form.
Codepen live demo:
In order to be able to send the data from form to our mailbox, we have to provide some server-side solution which will take care about all the required actions. In this tutorial we will choose PHP to create a small snippet of code that will be saved in separate file. After that, you have to open the HTML code of your the form and input the name of this PHP file as a value for action attribute in form element.
Let’s call the PHP file “contact.php”. The form element will looks like this:
<form id="js-form" action="contact.php" method="post"> … </form>
<?php $myemail = "firstname.lastname@example.org"; $name = $_POST['name']; $email = $_POST['email']; $phone = $_POST['phone'];
– note: In situation when you would use “GET” method for your form, you would also use $_GET array instead of $_POST.
Next thing is to create a template for email that will be sent to our mailbox. Sure, we can just write down what data we want to receive and let the PHP do its work, but the result we would get would not be that nice and friendly. Let’s create new variable called “message” which will contain whole template for the email. Inside this variable we will use the names of $name, $email and $phone variables to include the values (data) stored in these variables. This message can be pretty simple.
/* Message template */ $message = "Hi, This message has been sent by: Name: $name E-mail: $email Phone: $phone ";
Now let’s specify what data do we want to get and use mail() function to send them to our mailbox. We will provide all these data in form of parameters for this function. First parameter will be our email. Second parameter will be the subject of the mail. Let’s say the form is on your portfolio and you are looking for clients, so the subject can simply be “Job”. The last parameter will be the message ($message variable).
Whole syntax of mail() function is mail(to,subject,message,headers,parameters). The first three parameters – to, subject and message – are all required by default, the rest is optional and you can omit them as we will do today.
mail($myemail, “Jobs”, $message); ?>
– note: You can also specify your email address here in first parameter like “email@example.com” instead of using variable as we did in the beginning.
This is all you need to get the form send successfully to your mailbox. If you want to redirect the user somewhere after sending the form, use header(‘Location: ‘) with HTML file or address as value for Location.
Below is whole PHP code in one piece.
<?php $myemail = "firstname.lastname@example.org"; $name = $_POST['name']; $email = $_POST['email']; $phone = $_POST['phone']; /* Message template */ $message = "Hi, This message has been sent by: Name: $name E-mail: $email Phone: $phone "; mail($myemail, “Jobs”, $message); ?>
If you liked this article, then please consider subscribing.