Welcome to the Treehouse Community
The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

Christopher Nelson
Front End Web Development Techdegree Student 13,162 PointsForm submit using AJAX
I have a form I'm trying to submit using the POST method to an email address, The Email sends just fine but all the values are empty.
<form id="contact-form" action="mail-script.php" method="POST">
<label for="form-name">Name:</label>
<input type="text" name="name" id="form-name" placeholder="Enter Name">
<label for="form-email">Email:</label>
<input type="text" name="email" id="form-email" placeholder="Enter Email">
<label for="form-phone">Phone:</label>
<input type="text" name="phone" id="form-phone" placeholder=" Enter Phone Number">
<label for="form-message">Message:</label>
<textarea name="message" id="form-message"></textarea>
<input type="submit" class="form-button" id="form-submit" value="Send">
</form>
$(function(){
$('#form-submit').click(function(){
$.ajax({
type: 'POST',
url: 'mail-script.php',
data: $("#contact-form").serialize,
error: function(){
alert("error");
},
success: function(){
alert("success");
}
}) ;
return false;
});
});
<?php
$MailTo = 'contact@email.com';
$EmailSubject = 'New Message';
$body = <<<EOD
Name: $Name
Phone:$Phone
Email: $Email
Message: $Message
EOD;
mail($MailTo, $EmailSubject, $body)
?>
1 Answer

Iain Simmons
Treehouse Moderator 32,289 PointsYou need to actually call the serialize
method in your JavaScript/jQuery, by putting a set of parentheses after the method name:
$(function(){
$('#form-submit').click(function(){
$.ajax({
type: 'POST',
url: 'mail-script.php',
data: $("#contact-form").serialize(),
error: function(){
alert("error");
},
success: function(){
alert("success");
}
}) ;
return false;
});
});
And you'd probably be better off handling the form submit
event directly rather than the click
event on the submit button...
$(function(){
$('#contact-form').submit(function(event){
event.preventDefault();
$.ajax({
type: 'POST',
url: 'mail-script.php',
data: $(this).serialize(),
error: function(){
alert("error");
},
success: function(){
alert("success");
}
}) ;
});
});
carlos medina
12,511 Pointscarlos medina
12,511 PointsDid you grab the values from the post method?
I.E $Name = $_POST["field_name"]