'Data from new HTML form input field not being passed to email using PHP and JavaScript

This is my first post on the site. I added a new input field to a previously working HTML contact form in order to collect the user’s street address. Although all other input fields continue to pass data to the email generated after the form is submitted, data is not being passed to the email with the street address. I have copied below the associated HTML, PHP, and JavaScript files, as well as an example of what data is now sent to the email.

I truly appreciate any help with what I am doing wrong. I have spent over 8 hours trying to solve this problem, but so far have been unsuccessful. Thank you!

Here is an example of the data now being placed into the email generated. Notice that the only data NOT being passed is the text that was input into the street address field of the contact form (blank).

Name: Tim Spyridon
Address:
Phone Number: 513-662-1464
Message:
Made major changes to PHP script. This may work!

Here is the HTML code used for the contact form:

                  <!-- Form Starts -->
              <div id="contact_form">
                 <div class="form-group">
                    <label>Name <span class="required">*</span></label>
                    <input placeholder="Your Name" type="text" name="name" class="form-control input-field" required>                    
                     <label>Street Address and City <span class="required">*</span></label>
                    <input placeholder="Your Street Address and City" type="text" name="address" class="form-control input-field" required>  
                    <label>Email Address <span class="required">*</span></label>
                    <input placeholder="Your Email Address" type="email" name="email" class="form-control input-field" required>           
                    <label>Phone Number including Area Code <span class="required">*</span></label>
                    <input placeholder="Your 10-Digit Phone Number" type="tel" name="phone" class="form-control input-field" required>     
                    <label>Message <span class="required">*</span></label>
                    <textarea placeholder="Type your message here ..." name="message" id="message" class="textarea-field form-control" rows="3" required></textarea>
                 </div>
                <div class="text-right">
                 * Required Field
                </div>
                 <button type="submit" id="submit_btn" value="Submit" class="btn center-block">Send message</button>
              </div>

Here is my JavaScript code from a file called contact.js:

"use strict";
jQuery(document).ready(function($) {
    $("#submit_btn").on("click", function() {
        var proceed = true;
    //simple validation at client's end
    //loop through each field and we simply change border color to red for invalid fields       
    $("#contact_form input[required], #contact_form textarea[required]").each(function() {
        $(this).css('background-color', '');
        if (!$.trim($(this).val())) { //if this field is empty 
            $(this).css('background-color', '#FFDEDE'); //change border color to #FFDEDE   
            proceed = false; //set do not proceed flag
        }
        //check invalid email
        var email_reg = /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/;
        if ($(this).attr("type") === "email" && !email_reg.test($.trim($(this).val()))) {
            $(this).css('background-color', '#FFDEDE'); //change border color to #FFDEDE   
            proceed = false; //set do not proceed flag              
        }
    });

    if (proceed) //everything looks good! proceed...
    {
        //get input field values data to be sent to server
        var post_data = {
            'user_name': $('input[name=name]').val(),
            'user_address': $('input[name=address]').val(),
            'user_email': $('input[name=email]').val(),
            'phone': $('input[name=phone]').val(),
            'msg': $('textarea[name=message]').val()
        };

        //Ajax post data to server
        $.post('php/sendmail.php', post_data, function(response) {
            if (response.type === 'error') { //load json data from server and output message     
                var output = '<br><br><div class="error">' + response.text + '</div>';
            } else {
                var output = '<br><br><div class="success">' + response.text + '</div>';
                //reset values in all input fields
                $("#contact_form input, #contact_form textarea").val('');

            }
            $('html, body').animate({scrollTop: $("#contact_form").offset().top-50}, 2000);
        
            $("#contact_results").hide().html(output).slideDown();
        }, 'json');
    }
    });


//reset previously set border colors and hide all message on .keyup()
$("#contact_form  input[required=true], #contact_form textarea[required=true]").keyup(function() {
    $(this).css('background-color', '');
    $("#result").slideUp();
});
});

Here is my PHP script from a file called sendmail.php:

    <?php
if($_POST)
{
$to_email1      = "[email protected]"; //Recipient email, Replace with own email here
$to_email2      = "[email protected]"; //Recipient email, Replace with own email here
$email_subject  = "Message from Website Contact Form";

//check if its an ajax request, exit if not
if(!isset($_SERVER['HTTP_X_REQUESTED_WITH']) AND strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) != 'xmlhttprequest') {
    
    $output = json_encode(array( //create JSON data
        'type'=>'error', 
        'text' => 'Sorry Request must be Ajax POST'
    ));
    die($output); //exit script outputting json data
} 

//Sanitize input data using PHP filter_var().
$user_name = filter_var($_POST["user_name"], FILTER_SANITIZE_STRING);
$user_address = filter_var($_POST['user_address'], FILTER_SANITIZE_STRING);
$user_email = filter_var($_POST["user_email"], FILTER_SANITIZE_EMAIL);
$phone = filter_var($_POST["phone"], FILTER_SANITIZE_NUMBER_INT);
$message = filter_var($_POST["msg"], FILTER_SANITIZE_STRING);

  $message_body = "Name: " . $user_name . "\n"
  . "Address: " . $user_address . "\n"
  . "Email: " . $user_email . "\n"
  . "Phone Number: " . $phone . "\n"
  . "Message: " . "\n" . $message;
    
//proceed with PHP email.
$headers = 'From: '.$user_name.'' . "\r\n" .
'Reply-To: '.$user_email.'' . "\r\n" .
'X-Mailer: PHP/' . phpversion();

$send_mail = mail($to_email1, $email_subject, $message_body, $headers);
$send_mail = mail($to_email2, $email_subject, $message_body, $headers);

if(!$send_mail)
{
    //If mail couldn't be sent output error. Check your PHP email configuration (if it ever happens)
    $output = json_encode(array('type'=>'error', 'text' => '<p>Could not send mail! Please check your PHP mail configuration.</p>'));
    die($output);
}else{
    $output = json_encode(array('type'=>'message', 'text' => '<div class="alert alert-success" role="alert">
    Hi '.$user_name .', Thank you for your message! We will get back to you soon.</div>'));
    die($output);
}
}
?>


Solution 1:[1]

In support of the comment made last night (above ) here is the test version of the above script which appears to work perfectly well in terms of the newly added message field. There are comments at places where things were changed - some semantic, others functional.

<?php
    if( $_POST ){
        
        
        # Simple Boolean to switch between live & test mode
        # whilst testing that this script does or does not 
        # function correctly.
        $b_live=false;
        
        
        
        
        $to_email1      = "[email protected]"; //Recipient email, Replace with own email here
        $to_email2      = "[email protected]"; //Recipient email, Replace with own email here
        $email_subject  = "Message from Website Contact Form";

        //check if its an ajax request, exit if not
        if( !isset( $_SERVER['HTTP_X_REQUESTED_WITH'] ) AND strtolower( $_SERVER['HTTP_X_REQUESTED_WITH'] ) != 'xmlhttprequest' ) {
            $output = json_encode(array( //create JSON data
                'type'=>'error', 
                'text' => 'Sorry Request must be Ajax POST'
            ));
            die($output); //exit script outputting json data
        } 

        //Sanitize input data using PHP filter_var().
        $user_name = filter_var($_POST["user_name"], FILTER_SANITIZE_STRING);
        $user_address = filter_var($_POST['user_address'], FILTER_SANITIZE_STRING);
        $user_email = filter_var($_POST["user_email"], FILTER_SANITIZE_EMAIL);
        $phone = filter_var($_POST["phone"], FILTER_SANITIZE_NUMBER_INT);
        $message = filter_var($_POST["msg"], FILTER_SANITIZE_STRING);
        
        
        
        
        

        
        
        
        
        
        
        
        
        
        $message_body = "Name: " . $user_name . "\n"
          . "Address: " . $user_address . "\n"
          . "Email: " . $user_email . "\n"
          . "Phone Number: " . $phone . "\n"
          . "Message: " . "\n" . $message;
            
        //proceed with PHP email.
        $headers = 'From: '.$user_name.'' . "\r\n" .
        'Reply-To: '.$user_email.'' . "\r\n" .
        'X-Mailer: PHP/' . phpversion();
        
        
        
        # If the script is live, attempt to send the emails
        if( $b_live ){
            $send_mail = mail($to_email1, $email_subject, $message_body, $headers);
            $send_mail = mail($to_email2, $email_subject, $message_body, $headers);
        }else{
            
            # emulate either a success or failure randomly 
            # to aid testing of ajax callback
            $send_mail=mt_rand(0,1);
            
            # you can verify the message is being populated
            $_POST['MESSAGE']=$message;
            $_POST['TIME']=date( DATE_ATOM );
            
            file_put_contents( __DIR__ . '/ajax.log', json_encode( $_POST ) . PHP_EOL, FILE_APPEND );
        }

        if(!$send_mail){
            //If mail couldn't be sent output error. Check your PHP email configuration (if it ever happens)
            $output = json_encode(array('type'=>'error', 'text' => '<p>Could not send mail! Please check your PHP mail configuration.</p>'));
            die( $output );
            
        }else{
            
            $output = json_encode(array('type'=>'message', 'text' => '<div class="alert alert-success" role="alert">
            Hi '.$user_name .', Thank you for your message! We will get back to you soon.</div>'));
            die( $output );
        }
    }
?>

<!DOCTYPE html>
<html lang='en'>
    <head>
        <meta charset='utf-8' />
        <script src='//code.jquery.com/jquery-latest.js'></script>
        <title>Contact</title>
    </head>
    <body>
    
        <!--
            The `label` attribute **must** be associated with whichever form element
            it is supposed to reference. This can be done either by including the
            `for` attribute in the label with the input element's ID OR the form element
            must be within the label itself - as shown below.
        -->
        <div id="contact_form">
            <div class="form-group">
                <label>
                    Name <span class="required">*</span>
                    <input placeholder="Your Name" type="text" name="name" class="form-control input-field" required />
                </label>                    
                <label>
                    Street Address and City <span class="required">*</span>
                    <input placeholder="Your Street Address and City" type="text" name="address" class="form-control input-field" required />
                </label>  
                <label>
                    Email Address <span class="required">*</span>
                    <input placeholder="Your Email Address" type="email" name="email" class="form-control input-field" required />
                </label>           
                <label>
                    Phone Number including Area Code <span class="required">*</span>
                    <input placeholder="Your 10-Digit Phone Number" type="tel" name="phone" class="form-control input-field" required />
                </label>     
                <label>
                    Message <span class="required">*</span>
                    <textarea placeholder="Type your message here ..." name="message" id="message" class="textarea-field form-control" rows="3" required /></textarea>
                </label>
            </div>
            <div class="text-right">
                * Required Field
            </div>
            <button type="submit" id="submit_btn" value="Submit" class="btn center-block">Send message</button>
        </div>
        
        
        
        <!--
            Added this DIV to allow output to be rendered
        -->
        <div id='contact_results'></div>
        
        
        
        
        <script>
            "use strict";
            jQuery(document).ready(function($) {
                $("#submit_btn").on("click", function() {
                    var proceed = true;
                //simple validation at client's end
                //loop through each field and we simply change border color to red for invalid fields       
                $("#contact_form input[required], #contact_form textarea[required]").each(function() {
                    $(this).css('background-color', '');
                    if (!$.trim($(this).val())) { //if this field is empty 
                        $(this).css('background-color', '#FFDEDE'); //change border color to #FFDEDE   
                        proceed = false; //set do not proceed flag
                    }
                    //check invalid email
                    var email_reg = /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/;
                    if ($(this).attr("type") === "email" && !email_reg.test($.trim($(this).val()))) {
                        $(this).css('background-color', '#FFDEDE'); //change border color to #FFDEDE   
                        proceed = false; //set do not proceed flag              
                    }
                });

                if (proceed) //everything looks good! proceed...
                {
                    //get input field values data to be sent to server
                    var post_data = {
                        'user_name': $('input[name=name]').val(),
                        'user_address': $('input[name=address]').val(),
                        'user_email': $('input[name=email]').val(),
                        'phone': $('input[name=phone]').val(),
                        'msg': $('textarea[name=message]').val()
                    };




                    //Ajax post data to server
                    /*
                    *****************************************************
                        This is the ONLY change made in the Javascript
                    *****************************************************
                    */
                    const _URL=location.href;   // 'php/sendmail.php'
                    
                    $.post( _URL, post_data, function(response) {
                        if (response.type === 'error') { //load json data from server and output message     
                            var output = '<br><br><div class="error">' + response.text + '</div>';
                        } else {
                            var output = '<br><br><div class="success">' + response.text + '</div>';
                            $("#contact_form input, #contact_form textarea").val('');

                        }
                        $('html, body').animate({scrollTop: $("#contact_form").offset().top-50}, 2000);
                    
                        $("#contact_results").hide().html(output).slideDown();
                    }, 'json');
                }
                });


            //reset previously set border colors and hide all message on .keyup()
            $("#contact_form  input[required=true], #contact_form textarea[required=true]").keyup(function() {
                $(this).css('background-color', '');
                $("#result").slideUp();
            });
            });
        </script>       
    </body>
</html>

With this I could not replicate the issues stated in the question: The $message variable is populated and can be inspected in the console or the ajax.log file that is generated in test mode.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Professor Abronsius