How do I submit a form without refreshing the current page? - html

I have a fairly basic email form
<form name="contactform" method="post" action="send_email.php" id="email_form">
<div class="ContactHeaders">Name</div>
<input type="text" name="Name" class="ContactBoxes" id="name"/><br/><br/>
<div class="ContactHeaders">Email</div>
<input type="email" name="Email" class="ContactBoxes"/><br/><br/>
<div class="ContactHeaders">Message</div>
<div style="width:100%">
<textarea name="Message" maxlength="1000"></textarea><br/>
</div>
<div style="width: 100%">
<input type="submit" class="Submitbtn" value="Submit">
</div>
</form>
Here's 'send_email.php'
<?php
ob_start();
include 'navbar.php';
ob_end_clean();
if(isset($_POST['Email'])) {
//declare variables
$Name = $_POST['Name'];
$Email = $_POST['Email'];
$Message = $_POST['Message'];
$complete = 0;
$email_to = "someone#example.com";
$email_subject = "Website Contact";
//check all forms are filled in correctly
$email_exp = '/^[A-Za-z0-9._%-]+#[A-Za-z0-9.-]+\.[A-Za-z]{2,4}$/';
if(preg_match($email_exp,$Email)) {
$complete++;
}
$string_exp = "/^[A-Za-z .'-]+$/";
if(preg_match($string_exp,$Name)) {
$complete++;
}
if(strlen($Message) > 20) {
$complete++;
}
//send email if $complete = 4
if ($complete == 3){
if (get_magic_quotes_gpc()) {
$Message = stripslashes($Message);
}
$Message = $Message . "\n\n" . "From " . $Name;
$headers = 'From: '.$Email."\r\n".
'Reply-To: '.$Email."\r\n" .
'X-Mailer: PHP/' . phpversion();
#mail($email_to, $email_subject, $Message, $headers);
echo '<script>
alert("Thank you for contacting me. I will be in touch shortly");
top.location="index.php";
</script>';
}
else {
echo '<script>
alert("The form you submitted is invalid. Please ensure the following: \n You have provided a valid email address. \n Your phone number is entered correctly. \n The message box contains at least 20 characters.")
history.go(-1)
</script>';
}
}
?>
So my problem is that when the form submits to the php file, the browser loads the php file, runs the code and returns the result (It's not really a problem but it's something I don't want) It is then up to java to display the alert and go back one (in my code anyway). Is there a way to make it run the code in the background so the form runs the php file without having to go to it (if that makes sense) and return the result in the same window. I've obviously looked around and found loads of things about AJAX but I didn't really understand it and couldn't get it to work for me.
The reason for doing this is a little complicated but would make things much easier as far as user-friendliness goes for my site, as well as looking cleaner (going to a blank page and displaying an alert doesn't look very good).
Thanks in advance for any help you can offer me:)

$('.Submitbtn').click(function(e) {
e.preventDefault();
// do some form validation here
if form is valid { // from validation above
var formData = $('#email_form').serialize();
$.post('send_email.php',{data:formData});
} else {
alert('Form no good - fix it!');
return false;
}
});
Here's something you can start with. This is very basic but supplies the necessary foundation for beginning your AJAX adventure.
50 Excellent AJAX Tutorials

Related

"Send" Button linked to contact form

I have a contact form in my webpage with 3 areas of name, e-mail and text (no subject), and a send button underneath the form. What should I do to make the button work? I want the user to write their Name (which would eventually become the subject of the e-mail), their e-mail and the text they want to send and I want to receive the e-mail from them with their name as a subject, their e-mail and the text they would have written as the body of the e-mail. Plus, I don't want the button to open the users e-mail, like outlook etc. I want it to happent silently. So the outcome would be the user writes the text in the contact form, presses send and then I get the e-mail.
Thank you a lot, in advance!!!
Rafael.
First you have to learn php to make it work. You can not send mail using only form design.
Also, you have to upload your files on the server. Sending mail requires SMTP, which will not work on localhost.
HTML:
<form action="mail_handler.php" method="
FullName: <input type="text" name="full_name"><br>
Email: <input type="text" name="email"><br>
Message:<br><textarea rows="5" name="message" cols="30"></textarea><br>
<input type="submit" name="submit" value="Submit">
</form>
mail_handler.php
<?php
if(isset($_POST['submit'])){
$to = "email#example.com"; // this is your Email address
$from = $_POST['email']; // this is the sender's Email address
$full_name = $_POST['full_name'];
$subject = "Form submission";
$subject2 = "Copy of your form submission";
$message = $full_name . " wrote the following:" . "\n\n" . $_POST['message'];
$message2 = "Here is a copy of your message " . $full_name . "\n\n" . $_POST['message'];
$headers = "From:" . $from;
$headers2 = "From:" . $to;
mail($to,$subject,$message,$headers);
mail($from,$subject2,$message2,$headers2); // sends a copy of the message to the sender
echo "Mail Sent. Thank you " . $full_name . ", we will contact you";
}
?>
I suggest you to watch some tutorial before implementing it. You need to understand php before implementing it.

How do I make an email form in html that allows users to type a message then, in a new window, prompts them to send the message?

I want the user to input the message they want to send in a form, but after they click send, it brings up their email for them to send.
The only reason for this is because I don't have a server.
Is this possible?
Thanks
According to this question, you can do it with Javascript:
function sendMail() {
var link = "mailto:me#example.com"
+ "?cc=myCCaddress#example.com"
+ "&subject=" + escape("This is my subject")
+ "&body=" + escape(document.getElementById('myText').value)
;
window.location.href = link;
}
<textarea id="myText">Lorem ipsum...</textarea>
<button onclick="sendMail(); return false">Send</button>
using this function for sending email without server you can send mail using you mail id too
<?php
$to = 'nobody#example.com';
$subject = 'the subject';
$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);
?>
If you want to send emails, a good approach (there are multiples) is to use php to send your email.
You will have an html like this for example:
<form action="action_page.php">
Email:<br>
<input type="text" name="email">
<br>
Text:<br>
<input type="text" name="Text">
<br><br>
<input type="submit" value="Submit">
</form>
<p>If you click "Submit", the form-data will be sent to a page called "action_page.php".</p>
Then in php:
<?php
$receiver = "empf#domain.de";
$subject = "Die Mail-Funktion";
$from = "From: Nils Reimers <absender#domain.de>";
$text = "Hier lernt Ihr, wie man mit PHP Mails verschickt";
mail($receiver, $subject, $text, $from);
?>
You should look up on how to get your input data from your form to php...

HTML Contact Form Send Mail Through PHP

I have this code for a contact form in html:
<form method=post action=sendmail.php>
<div class=one_third>
<label>Name</label>
<input type=text name=author value id=name />
</div>
<div class=one_third>
<label>Email</label>
<input type=text name=email value id=email />
</div>
<div class="one_third last">
<label>Subject</label>
<input type=text name=subject value id=subject />
</div>
<div class=full_width>
<label>Your Message</label>
<textarea name=msg id=msg></textarea>
</div>
<input type=submit name=submit value=Submit />
</form>
I would likes to know if you can provide me with a php code, to go inside "sendmail.php" that will actually send the email.
First of all, you should try to look for answers before you post questions, this is pretty much what the first result of googling "php send mail" will show you:
<?php
if (isset($_REQUEST['email']))
//if "email" is filled out, send email
{
//send email
$from = $_REQUEST['author'] ;
$to = $_REQUEST['email'] ;
$subject = $_REQUEST['subject'] ;
$message = $_REQUEST['msg'] ;
mail($to, $subject, $message, "From:" . $from);
// the mail was sent
echo "Thank you for using our mail form";
}
else {
//if "email" is not filled out, display the form
//just close php and copy the code for your form
?>
- paste your html form here -
<?php
}
?>
The second thing is, I don't know what do you want to do with your author field. I suspect you have never sent an email with you having to enter who you are in any input field. The client kind of does that for you. So, with that in mind, I just left author at the bottom of the message.
This all providing you have a working email system set up in php.ini configuration settings.
Here you go bud this will work with your form you posted above if you have questions let me know.
<?php
/* Subject and email variables */
$emailsSubject = 'This is where you type what you subject will show up as';
$webMaster = 'youremail#gmail.com';
/* Gathering Data Variables - Whats in the form */
$name = $_POST ['name'];
$email = $_POST ['email'];
$subject = $_POST ['subject'];
$msg = $_POST['msg'];
/*Security*/
/* What You Want To See In The Email Place Inbetween $body = <<<EOD and EOD; */
$body = <<<EOD
<strong>Client:</strong> $name
<br />
<br />
<strong>Email:</strong> $email
<br />
<br />
<strong>Subject:</strong> $subject
<br />
<br />
______________________________________________
<br />
<br />
$msg
EOD;
/* Headers is a tag containing the users email and how you want it to display in your email */
$headers = "From: $email\r\n";
$headers .= "Content-type: text/html\r\n";
/* This is what sends the email */
$success = mail($webMaster, $emailsSubject, $body, $headers);
/* Results Rendered as Html */
echo file_get_contents("http://yourdomain.com/after-message-sent/");
?>
For the "echo file_get_contents" you can create a page that you want your client to see after that tells them there message was sent. If you want it plain Jane then just echo Your message was sent. Hope this helps.

PHP Mail() Function Issue - Message field not getting sent (WordPress)

I know there are thousands and thousands of ways to utilize the PHP mail() function, but I am fairly new to PHP and could use some pointers to get me set in the right direction. I have a PHP mail function written into my WordPress driven site and it emails all the information (name, email, & phone) except for the message field. I've done my research on here as well as every PHP related site, but I would prefer to understand my specific issue so I can better understand what I'm writing. So with that said...here's the code:
<?php
function spamcheck($field)
{
$field=filter_var($field, FILTER_SANITIZE_EMAIL);
if(filter_var($field, FILTER_VALIDATE_EMAIL))
{
return TRUE;
}
else
{
return FALSE;
}
}
if (isset($_POST['email']))
{
$mailcheck = spamcheck($_POST['email']);
if ($mailcheck==FALSE)
{
$submit_message = "Please input your information again.";
}
else
{
$name = $_POST['name'];
$email = $_POST['email'];
$phone = $_POST['phone'];
$message = $_POST['message'];
mail("emailaddress#gmail.com", "From: $name", "Email: $email", "Phone Number: $phone", "Message: $message");
$submit_message = "Thank you for your message";
}
}
?>
And the HTML...
<form name="message-me" id="contact-form" action="<?php echo $_SERVER['REQUEST_URI']; ?>" method="POST" enctype="multipart/form-data">
<div class="field-group">
<label>Name:</label><input type="text" name="name" id="form_name" />
</div>
<div class="field-group">
<label>Email:</label><input type="text" name="email" id="form_email" />
</div>
<div class="field-group">
<label>Phone:</label><input type="text" name="phone" id="form_phone" />
</div>
<div class="field-group">
<label>Message:</label><textarea rows="4" cols="31" name="message" id="form_message"></textarea>
</div>
<div class="field-group">
<input type="image" src="<?php bloginfo('template_directory'); ?>/images/Send-Message-Arrow.png" width="90" height="72" class="form-button" />
</div>
</form>
Any information would be greatly appreciated. As I mentioned, I'm still learning PHP and I really want to understand what I'm writing - not just blindly copying & pasting code all the time. Thanks!
Your SMTP want to be configured, first check up that
and
//Header Information for mail
$headers = "YOUR HEADERS INFORMATION HERE";
$msg="Email: $email<br/>Phone Number: $phone<br/>Message: $message";
mail("emailaddress#example.com", $subject, $msg, $headers);
Please have look at Documentation.
You need to provide parameters as
mail($to, $subject, $message, $headers);
Here you have provided "to" email address right.
So this might help you:
$message = $_POST['message'];
//Give mail a subject
$subject = "YOUR SUBJECT HERE";
//Header Information for mail
$headers = "YOUR HEADERS INFORMATION HERE";
mail("emailaddress#gmail.com", $subject, $message, $headers);
$submit_message = "Thank you for your message";
Enjoy!
Kindly read this manual with the directives and examples on it and you'll understand well what you are doing. Just take your time to read and understand well then start asking your questions from that point. Right now, you don't seem to understand even how the PHP mail() works. Read then get back so together you'll understand any solutions pointed out to you and you won't just copy and paste the solution without being able to solve it tomorrow.
http://php.net/manual/en/function.mail.php

How To Display Error Messages With Wufoo API V3?

I am using the Wufoo API V3 to submit data from a form hosted on my website to my Wufoo account. I followed the example on the [Entries POST API][1] page, and I was able to successfully the data to my account.
I was wondering how I am able to check for error messages, and display the ErrorText for each text input field using PHP?
For example, if someone does not provide their email address in a required email field.
Here is the code I have so far:
<?
function submit() {
$ref = curl_init('https://myname.wufoo.com/api/v3/forms/xxxxxx/entries.json');
curl_setopt($ref, CURLOPT_HTTPHEADER, array('Content-type: multipart/form-data'));
curl_setopt($ref, CURLOPT_POST, true);
curl_setopt($ref, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ref, CURLOPT_POSTFIELDS, getPostParams());
curl_setopt($ref, CURLOPT_USERPWD, 'XXXX-XXXX-XXXX-XXXX');
curl_setopt($ref, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
curl_setopt($ref, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ref, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($ref, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ref, CURLOPT_USERAGENT, 'Wufoo.com');
$response = curl_exec($ref);
echo $response;
}
function getPostParams() {
return array( 'Field4' => "you#company.com");
}
submit();
?>
UPDATE (Nov 12, 2011):
MinisterOfPower,
Thanks for [the reply and advice][2] about the Wufoo PHP API Wrapper. I am now using the API Wrapper and it rocks. I am having some challenges integrating the code you provided with my form.
For example, if I have a form on index.php (see below) with an email required field. How would I be able to set up the API wrapper to display an error next to the appropriate input field after the form is submitted?
Here's the code for index.php:
<? require_once('my-wrapper.php'); ?>
<html>
<head>
<title>Form</title>
</head>
<body>
<form id="form1" name="form1" autocomplete="off" enctype="multipart/form-data" method="post" action="">
<div>
<label id="email" class="icons" for="Field4">Email</label>
<input id="Field4" name="Field4" type="text" class="formreg"/>
</div>
<div>
<label id="name" class="icons" for="Field6">Name</label>
<input id="Field6" name="Field6" type="text" class="formreg"/>
</div>
<input type="submit" name="saveForm" value="Submit" id="submit" class="submit" />
<input type="hidden" id="idstamp" name="idstamp" value="xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx=" />
</form>
</body>
</html>
Here's the code for my-wrapper.php:
$wrapper = new WufooApiWrapper('XXXX-XXXX-XXXX-XXXX', 'mysubdomain','wufoo.com');
$postArray = array();
foreach ($this->postValues as $value => $key) {
$postArray[] = new WufooSubmitField($key, $value);
}
try {
$result = $wrapper->entryPost('XXXXXX', $postArray);
if (!$result->Success) {
foreach ($result->FieldErrors as $key => $value) {
echo "Error on $key. Error Text: $value <br />";
}
}
} catch (Exception $e) {
//Read the error message.
}
UPDATE (Nov 20, 2011):
I am now able to display the error messages with the help of MinisterofPower's code and the Wufoo API wrapper. I have a couple of follow up questions:
I was wondering how I do set up the form below with PHP so that it posts the entries upon pressing the submit button?
Is it possible to do this using AJAX so the page does not refresh?
Here's the code:
<?
// API
require_once('WufooApiExamples.php');
// Wufoo
$wrapper = new WufooApiWrapper('XXXX-XXXX-XXXX-XXXX', 'mysubdomain','wufoo.com');
// Post Entries
$postArray = array();
foreach ($this->postValues as $key => $value) {
$postArray[] = new WufooSubmitField($key, $value);
}
try {
$result = $wrapper->entryPost('xxxxxx', $postArray);
if (!$result->Success) {
foreach ($result->FieldErrors as $key => $value) {
$fieldError[$value->ID] = $value->ErrorText;
}
}
} catch (Exception $e) {
//Read the error message.
}
// Add Errors
function addErrors($fieldName, $fieldError, $add){
if($fieldError[$fieldName] != ''){
if ($add == 'message') return '<p class="errors">'.$fieldError[$fieldName].'</p>';
else if ($add == 'class') return 'class ="errors"';
}
}
?>
<!--Begin Form-->
<div <? echo addErrors('Field4', $fieldError, 'class') ?>>
<label id="profile" class="icons" for="Field4">Email</label>
<input id="Field4" name="Field4" type="text" class="formreg" tabindex="1"/>
<? echo addErrors('Field4', $fieldError, 'message')?>
</div>
<div <? echo addErrors('Field6', $fieldError, 'class') ?>>
<label id="profile" class="icons" for="Field6">Name</label>
<input id="Field6" name="Field6" type="text" class="formreg" tabindex="1"/>
<? echo addErrors('Field6', $fieldError, 'message')?>
</div>
<!--End Form-->
The process of retrieving the response is outlined in the API docs. Also, the markup for field errors in found the Dealing With Failure section.
Is is worth nothing that Wufoo offers API Wrappers for PHP and many other languages. I highly suggest using one of those since they make the process so much easier.
Using the Wufoo API, you'd search for a Success value of 0 in the response object and then parse the Field Errors node, as shown here:
$wrapper = new WufooApiWrapper($this->apiKey, $this->subdomain, 'wufoo.com');
$postArray = array();
foreach ($this->postValues as $value => $key) {
$postArray[] = new WufooSubmitField($key, $value);
}
try {
$result = $wrapper->entryPost($this->formHash, $postArray);
if (!$result->Success) {
foreach ($result->FieldErros as $key => $value) {
echo "Error on $key. Error Text: $value <br />";
}
}
} catch (Exception $e) {
//Read the error message.
}
A followup question was posted above, so I'll add my answer here.
You asked how to display an error next to the form in question. You could do this with either javascript or php. I'll show you the PHP way only.
Using PHP, you could redirect back to the form with a value in the GET param of the URL, enumerating the error fields and messages. So, for example, you could do this:
for($result->FieldErrors as $name => $value) {
$str.="$name=$value&";
}
if($str) {
$str = '?errors=true&'.$str;
$host = $_SERVER['HTTP_HOST'];
$uri = rtrim(dirname($_SERVER['PHP_SELF']), '/\\');
header("Location: http://$host$uri/$str");
exit;
}
Then, you'd wrap the above code in this if statement to check for error values on postback, like so:
if($_GET['errors']) {
require_once('my-wrapper.php');
else
//Your HTML HERE
endif
After that, add some PHP conditions which append class names to your fields if they contain errors. For example:
<label id="Field4" class="icons <?php if ($_GET['Field4']) echo 'error'; ?>" for="Field4">Email</label>
Finally, add some CSS to call out the error fields with a color or other indicator.
The other way to do this is with javascript.
Use the same logic as above, but add the following script to your page (grabbed from here and here.)
<script type="text/javascript" charset="utf-8">
function getQueryVariable(variable) {
var query = window.location.search.substring(1);
var vars = query.split("&");
for (var i=0;i<vars.length;i++) {
var pair = vars[i].split("=");
if (pair[0] == variable) {
return 'error';
}
}
}
function changeClass (elementID, newClass) {
var element = document.getElementById(elementID);
element.setAttribute("class", newClass); //For Most Browsers
element.setAttribute("className", newClass); //For IE; harmless to other browsers.
}
changeClass('Field4', 'error');
</script>
Then use this markup instead:
<label id="Field4" class="icons" for="Field4">Email</label>
Good luck.
PS: This code was written here in SO, so it will probably contain syntax errors. But you can get the point...