Search code examples
phpjqueryfunctionemailpost

How to send an email using jQuery and POST


Update: Final working code is at the very bottom of question I left the rest of the code so you can see the process hope it helps someone in the future.

I am trying to send an email to myself (which is working) using only jQuery and an external php file, however, the email isn't picking up any of the data. I have the following code.

HTML

<section>
    <form enctype="multipart/form-data">
        <fieldset class="margin-b">
            <legend>Contact Me</legend>
            <label for="form_name">Name:<input name="form_name" id="form_name" type="text" value="" required autofocus ></label>
            <label for="form_email">Email:<input type="email" name="form_email" id="form_email" value=""></label>
            <label for="form_msg">Message:<textarea name="form_msg" id="form_msg" rows="5"></textarea></label>
        </fieldset>
        <input type="submit" name="submit" id="submit" value="Submit">
    </form>
</section>

JS

var data = {
  name: $("#form_name").val(),
  email: $("#form_email").val(),
  message: $("#form_message").val()
};
$.ajax({
  type: "POST",
  url: "email-php.php",
  data: data,
  success: function(){
    $('.success').fadeIn(1000);
  }
});

PHP

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

  //send email
  mail("[email protected]", "From: " .$email, $message);
}
?>

EDIT: I took the above from various answers on Stack Overflow however couldn't figure out what I am missing or doing wrong. I took most of it from this question here jQuery AJAX form using mail() PHP script sends email, but POST data from HTML form is undefined

UPDATE: After @inarilo's suggestion below I have changed everything to the following and now I don't get an email at all. This definitely looks like the better option so I would like to get it to work.

HTML

    <section>
    <form enctype="multipart/form-data" id="frmemail">
        <fieldset class="margin-b">
            <legend>Contact Me</legend>
            <label for="form_name">Name:<input name="form_name" type="text" value="" required autofocus ></label>
            <label for="form_email">Email:<input type="email" name="form_email" value=""></label>
            <label for="form_msg">Message:<textarea name="form_msg" rows="5"></textarea></label>
        </fieldset>
        <input type="submit" name="submit" id="submit" value="Submit">
    </form>
</section>

JS

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

PHP

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

  //send email
  mail("[email protected]", "From: " .$email, $message);
}
?>

Final Working Code

HTML

<section>
  <form enctype="multipart/form-data" id="frmemail">
    <fieldset class="margin-b">
      <legend>Contact Me</legend>
      <label for="form_name">Name:<input name="form_name" type="text" value="" required autofocus ></label>
      <label for="form_email">Email:<input name="form_email" type="email" value=""></label>
      <label for="form_msg">Message:<textarea name="form_msg" rows="5"></textarea></label>
    </fieldset>
    <input type="submit" name="submit" id="submit" value="Submit">
  </form>
</section>

JS

$(document).ready(function() {
  $('#frmemail').submit(function(event) {
    $.ajax({
      type: 'POST',
      url: 'email-php.php',
      data: $('#frmemail').serialize(),
      success: function() {
        $('.success').fadeIn(1000)
      }
    })
  })
})

PHP

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

$to = "[email protected]";
$subject = "RIA Emails";
$body = "Name: ".$name."\nEmail: ".$email."\nMessage: ".$message;
$headers = "From: " . $email;

//send email
mail($to, $subject, $body, $headers);
?>

Solution

  • You have multiple errors, first of all you are using element ids to pick up the data:

    name: $("#form_name").val(),
    email: $("#form_email").val(),
    message: $("#msg_text").val()
    

    but the input elements themselves have no id attribute defined.

    Secondly, you are passing name, email and message, but in your PHP you are using name, email and text:

    $name = $_POST['name'];
    $email = $_POST['email'];
    $message = $_POST['text'];
    

    However, even if correct all this is unnecessarily complicated, you can instead just serialize the form:

    In the HTML, add an id to the form:

    <form enctype="multipart/form-data" id="frmemail">
    

    In JS, pick up the form and serialize it:

    $(document).ready(function(){
      $("#frmemail").submit(function(event){
        event.preventDefault();
        $.ajax({
          type: "POST",
          url: "email-php.php",
          data: $("#frmemail").serialize(),
          success: function(){
            $('.success').fadeIn(1000);
          }
        });
      });
    });
    

    And in PHP simply use the element names, you don't need ids for them:

    $name = $_POST['form_name'];
    $email = $_POST['form_email'];
    $message = $_POST['form_msg'];