How to send an email using jQuery and POST

14,530

Solution 1

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'];

Solution 2

you are trying to get textarea value by using wrong id, it should be:

message: $("#form_msg").val()

not

message: $("#form_email").val()

and in php file, replace the following:

$message = $_POST['text'];

with

$message = $_POST['message'];

that's it :)

Share:
14,530

Related videos on Youtube

Landon Call
Author by

Landon Call

Front End web developer building websites for several companies under a major corporation. Sometimes we all forget things which is why we are all here.

Updated on May 25, 2022

Comments

  • Landon Call
    Landon Call about 2 years

    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);
    ?>
    
    • tan
      tan almost 7 years
      more typo, there is no 'text' you are posting with ajax.
    • Landon Call
      Landon Call almost 7 years
      @tan can you explain further, please?
    • Himanshu Upadhyay
      Himanshu Upadhyay almost 7 years
      ok @LandonCall Amrinder Singh's answer is correct then.
    • tan
      tan almost 7 years
      still not ok, its #form_msg not #form_message :-)
  • Landon Call
    Landon Call almost 7 years
    Not sure how it got changed to #form_email it was at one point #form_msg. but the above changes still didn't work. I find it strange that the data I am inputting is going up into the URL. I thought this didn't happen with POST? I'll update my code to include the above fixes.
  • Landon Call
    Landon Call almost 7 years
    Ok, I have adjusted my question to include all your fixes and still, my emails come into my inbox blank.
  • Sᴀᴍ Onᴇᴌᴀ
    Sᴀᴍ Onᴇᴌᴀ almost 7 years
    Please don't edit the original code in your question- otherwise it may make the answers seem off/incorrect. If you want to add updates then just add to the end, stating what has changed- common conventions include adding a heading like Update:
  • Landon Call
    Landon Call almost 7 years
    Thanks @SamOnela will do from now on I figured there was a way to see past edits.
  • Landon Call
    Landon Call almost 7 years
    Still no data. I thought I wasn't getting the emails at all but I accidentally had two .com
  • Amrinder Singh
    Amrinder Singh almost 7 years
    it should be $("#form_msg"), you are again putting it wrongly, now you have put it as "form_message", it should be "form_msg"
  • Newbie
    Newbie almost 7 years
    have you tried to check the data you are trying to use in the php. if not, echo those data first, then let it show in your jquery code by using : success: function(data){ alert(data); }
  • Landon Call
    Landon Call almost 7 years
    I tried to do that but I think I was doing it wrong and now with the new code I am not sure how to echo it out because it isn't being saved to an object.
  • Landon Call
    Landon Call almost 7 years
    I have updated my code with your suggestion but it's still not working. Also it seems weird to me that everything is being added to the URL. You can test this on my server if you would be so kind 3760.ljazzstudios.com/email-post/jquery.php
  • Landon Call
    Landon Call almost 7 years
    After submitting the form my url turns to this 3760.ljazzstudios.com/email-post/… is that normal?
  • Newbie
    Newbie almost 7 years
    first, I suggest to put id names on your input forms. then call then in your jquery: for example : $('#submit').on('click',function(){ var name = $('#name').val(), email = $('#email').val(); alert(name or email); // check first if you get the data from your input form });
  • inarilo
    inarilo almost 7 years
    can you please update your question with the full js code?
  • inarilo
    inarilo almost 7 years
    the form is being submitted, the default form method is GET, but what you actually need is to stop it from submitting.
  • Landon Call
    Landon Call almost 7 years
    Now my submit button doesn't do anything.
  • Landon Call
    Landon Call almost 7 years
    After changing my JS to match yours but taking out the event.preventDefault(); I now get my message!!! Not sure if my subject is working properly but that I think I can figure out now.
  • Landon Call
    Landon Call almost 7 years
    One more question why is it that mail("[email protected]", $subject, "From: " .$email, $message); gives me a message of jQuery method is working!!! From: [email protected] I figured the From: part would come before the message due to the order of the code but this doesn't seem to be the case.
  • Landon Call
    Landon Call almost 7 years
    Solved my issue. :D I will add all my final code in the main question in case someone else is looking for an answer.
  • inarilo
    inarilo almost 7 years
    preventDefault() is needed to prevent submission because you are using AJAX instead for sending data.
  • Adarsh Singh
    Adarsh Singh over 4 years
    It says 405 method not allowed.