I am having trouble getting my javascript hyperlink button to post data to my php form email script. I have tried doing it several different ways, but nothing seems to work. Any help is appreciated. Thank you.
My form code:
<form id="form" action="contactform.php" method="POST" enctype="text/plain" >
<fieldset>
<label><strong>Your Name:</strong><input id="name" type="text" name="name"> </label>
<label><strong>Your Phone Number:</strong><input id="phone" type="text" name="phone"></label>
<label><strong>Your E-mail:</strong><input id="email" type="text" name="email"></label>
<label><strong>Your Message:</strong><textarea id="message" name="message"></textarea></label>
<div class="btns"><a href="contacts.html" class="button">Clear</a><a href="#" onclick="document.getElementById('form').submit();" class="button">Send</a></div>
</fieldset>
</form>
Contactform.php:
<?php
var_dump($_POST);
if (isset($_POST['form'])) {
$name = $_POST['name'];
$phone = $_POST['phone'];
$visitor_email = $_POST['email'];
$message = $_POST['message'];
$email_from = 'emailaddress@gmail.com';
$email_subject = "Contact Form Submission";
$email_body = "Name: $name\n" . "Phone: $phone\n" . "Messge: $message";
$to= 'emailaddress@gmail.com';
$headers= "From: $email_from \r\n";
$headers.= "Reply-To: $visitor_email \r\n";
mail($to,$email_subject,$email_body,$headers);
echo "Thank you for your interest. I will contact you shortly.";
}else{
echo "It didn't work.";
}
?>
Also, I have the var_dump at the beginning of the php for debugging purposes only. Not going to be a part of the final code.
Just replace
a
tag as below.and also replace
document.forms["myForm"].submit();
and add
name="myForm"
to your form.Complete Code
I tested this and it works....
Some other tips for you to consider are:
<strong>
. instead use css classes as you did with the hyperlink. examplelabel { font-weight:bold }
or<label class='strong'>
$("form").first().on("submit",function...
<label for="input1">
to match to an input and enable a checkbox when the text is clicked for example.This will work:
You don't need to
getElementById
, you can simply reference it this way.While I know this does not answer your question there is no reason to use Javascript for this purpose (in the example above) as the HTML input elements will handle both of these functions automatically.
I would only work on doing something like this for validating data and then I'd use the
onsubmit
action of the form (returning false if validation fails).Remove
enctype="text/plain"
from the form tag, PHP doesn't support it.See: method="post" enctype="text/plain" are not compatible?