Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery AJAX form using mail() PHP script sends email, but POST data from HTML form is undefined

Thanks for taking the time to look, guys. I'm creating a pretty basic AJAX contact form using jQuery. The email sends, but upon opening the email there is no POST data, so I just get the strings I defined in the PHP script. On my phone's email client, the content of the email literally says 'undefined'. I've tried adding different types of header data to no avail, and a number of variations on the PHP mail() function.

I am more than willing to adopt an easier solution for a simple AJAX form, so thanks in advance for any new approaches.

Here is the form:

   <section id="left">
      <label for="form_name">Name</label>
      <input name="form_name" id="form_name" type="text" >

      <label for="form_email">Email</label>
      <input name="form_email" id="form_email" type="email" >
   </section>

   <section id="right">
      <label for="form_msg">Message</label>
      <textarea name="form_msg" id="form_msg"></textarea>
      <input id="submit" class="button" name="submit" type="submit" value="Send">
   </section>

</form>

The jQuery AJAX:

$(function() {
    $("#contact .button").click(function() {
        var name = $("#form_name").val();
        var email = $("#form_email").val();
        var text = $("#msg_text").val();
        var dataString = 'name='+ name + '&email=' + email + '&text=' + text;

        $.ajax({
            type: "POST",
            url: "email.php",
            data: dataString,
            success: function(){
            $('.success').fadeIn(1000);
            }
        });

        return false;
    });
});

The PHP script (external file 'email.php'):

<?php
if($_POST){
    $name = $_POST['form_name'];
    $email = $_POST['form_email'];
    $message = $_POST['form_msg'];

//send email
    mail("[email protected]", "This is an email from:" .$email, $message);
}
?>
like image 857
Jason Sears Avatar asked Mar 08 '13 18:03

Jason Sears


1 Answers

There is no need to make a query string. Just put your values in an object and jQuery will take care of the rest for you.

var data = {
    name: $("#form_name").val(),
    email: $("#form_email").val(),
    message: $("#msg_text").val()
};
$.ajax({
    type: "POST",
    url: "email.php",
    data: data,
    success: function(){
        $('.success').fadeIn(1000);
    }
});
like image 196
Seain Malkin Avatar answered Nov 11 '22 13:11

Seain Malkin