Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialChristopher 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,305 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"]