Issue with PHP and Jquery contact form causing blank emails to be sent

I've been on the hunt for a solution, but nothing seems to work from other topics I've seen. So, I'm reaching out with my query now. Apologies if it overlaps with another question.

Below is the html markup within <head></head>

    <script src="http://code.jquery.com/jquery-1.11.3.min.js"></script>
     ....
    <style>
    .error { display:none; }
    .success { display:none; }
    </style>


<script type="text/javascript">
    $(document).ready(function(){
        $('#send_message').submit(function(e){
            e.preventDefault();
            var error = false;
            var name = $('#name').val();
            var email = $('#email').val();
            var message = $('#message').val();
            if(name.length == 0){
                var error = true;
                $('#name_error').fadeIn(500);
            } else {
                $('#name_error').fadeOut(500);
            }
            if(email.length == 0 || email.indexOf('@') == '-1'){
                var error = true;
                $('#email_error').fadeIn(500);
            } else {
                $('#email_error').fadeOut(500);
            }
            if(message.length == 0){
                var error = true;
                $('#message_error').fadeIn(500);
            } else {
                $('#message_error').fadeOut(500);
            } if(error == false){
                $('#send_message').attr({'disabled' : 'true', 'value' : 'Sending...' });
                $.post("send_message.php", $("#contact_form").serialize(),function(result){
                    if(result == 'sent'){
                        $('#cf_submit_p').remove();
                        $('#mail_success').fadeIn(500);
                    } else {
                        $('#mail_fail').fadeIn(500);
                        $('#send_message').removeAttr('disabled').attr('value', 'Send');
                    }
                });
            }
        });
    });
</script>

In the <body></body>

<div class="container-fluid">
                        <p id="returnmessage"></p>
                        <form action="send_message.php" id="contactForm" method="post">
                            <h2 style="font-size:14px;line-height:18px;font-weight:600;padding-bottom:0;">Contact Us</h2>
                            <ul class="contactform">
                                <li>
                                    <div id="name_error" class="error" style="color:#aa3939; font-size:8px; line-height:8px;"> <i class="fa fa-exclamation"></i> Please enter your name.</div>
                                    <span class="contact-input-icon" style="text-align:left"><i class="fa fa-user"></i></span>
                                    <div class="input-field">
                                        <input type="text" style="border:1px solid rgba(220,220,220,0.5)" name="name" id="name" value="" class="required requiredField" placeholder="Full Name"/>
                                    </div>
                                </li>
                                <li>
                                    <div id="email_error" class="error" style="color:#aa3939; font-size:8px; line-height:8px;"> <i class="fa fa-exclamation"></i> Please enter your email address.</div>
                                    <span class="contact-input-icon"><i class="fa fa-envelope"></i></span>
                                    <div class="input-field">
                                        <input type="email" style="border:1px solid rgba(220,220,220,0.5)" name="email" id="email" value="" class="required requiredField email" placeholder="Email"/>
                                    </div>
                                </li>
                                <li class="textarea">
                                    <div id="message_error" class="error" style="color:#aa3939; font-size:8px; line-height:8px;"> <i class="fa fa-exclamation"></i> Please enter your message.</div>
                                    <span class="contact-input-icon"><i class="fa fa-pencil"></i></span>
                                    <div class="input-field">
                                        <textarea name="message" style="border:1px solid rgba(220,220,220,0.5)" id="message" rows="6" cols="20" class="required requiredField" placeholder="Your Message"></textarea>
                                    </div>
                                    <div id="mail_success" class="success" style="color:#00CC00"><i class="fa fa-check"></i> Thank you for your interest. We will be in touch soon.</div>
                                    <div id="mail_fail" class="error" style="color:#aa3939"><i class="fa fa-times"></i> Sorry, your message could not be delivered. Please try again later.</div>
                                </li>
                                <li class="buttons">
                                    <input type="hidden" style="border:1px solid rgba(220,220,220,0.5)" name="submitted" id="submitted" value="true" />
                                    <button type="submit" style="border:1px solid #3f97cf" class="button cf_submit_p" id="send_message"><i class="fa fa-paper-plane-o" style="font-size:20px;color:#3f97cf"></i></button>
                                </li>
                            </ul>
                        </form>
                    </div> <!--end container-fluid-->

and in send_message.php file;

    <?php

    if($_SERVER['REQUEST_METHOD'] === 'POST'){

    // Gather variables first.
    $email_to =   '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="a9d0ccddccdbc2c8dbc89099e9cec4c8c0c587cac6c4">[email protected]</a>'; 
    $name     =   $_POST['name'];
    $email    =   $_POST['email'];
    $message  =   $_POST['message'];

    $msgTo = "From: $name \r\nEmail: $email \r\nMessage: \r\n$message";

    /*$header variable for additional options. This way, when reply or forward,
     mailbox knows who to respond to */
    $headers  = "FROM: $email\r\n";
    $headers .= "REPLY-TO: $email\r\n";


    if(mail($email_to, $msgTo, $headers)){
        echo 'sent'; 
    }else{
        echo 'failed';
    }

}
?>

There seems to be an issue, despite checking class and ID names multiple times and making adjustments. It appears that the form isn't capturing the values properly. The validation works well, showing success messages after submission and sending emails. However, only the From, Message, Email parts seem to have trouble grabbing the variables.

Could you lend a helping hand?

Best regards,

Vis.

Answer №1

The ID for your form is contactForm, and you are utilizing the selector #contact_form.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The issue of JQuery and document ready being triggered multiple times while loading data into a control

Ever since implementing the load function to load content into a DIV upon document ready, I've noticed that all associated functions are firing multiple times (often twice, and sometimes endlessly). The scripts included in the head tag of all pages a ...

Error in displaying source and target arrowheads while using the Manhattan router with jointJS/Rappid

Is there a way to ensure that a specific cell is always positioned to the back, allowing for a graph to be placed on top of it seamlessly? When using the Manhattan router, I have noticed that the source and target arrowheads do not display correctly in thi ...

Dynamic content causing the img src value to remain unchanged

Inspect the code provided below. My goal is to show an image in real time when an image file is selected. The code snippet I have currently is functioning properly, but I am encountering a roadblock on this particular line $(".hpicFile").closest( ...

The first Ajax request is successful, however, the final one is failing to properly pass the data to the designated page

I have encountered an issue with two parsing scripts. The message.php script works without any problems, but when attempting to send data to data.php, the following error occurs: "Notice: Undefined index: userid in D:\xampp\htdocs\metro&b ...

Explore ways to incorporate special symbols in a jQuery array

I'm looking to include special characters in a jQuery array. I'm not quite sure how to do this. Currently, my code is: $scope.categories = ['Red', 'White', 'Rose', 'Sparkling']; and I would like it to be: ...

Having trouble downloading files in React and Node.js

I need to retrieve a specific file from the uploads folder and download it into my download folder. Both folders are located in the same directory, and the file's name is BasicUserFile-id.jpg. On my second attempt, I tried hardcoding the file name bu ...

Getting a 400 Bad Request error while trying to send JSON data to a PHP page via socket

Currently, I am in the process of developing a program that can gather temperature and humidity data from a Pysense device and then store this information in a database on my laptop. To accomplish this, I have set up a socket to send Json data via POST to ...

"When trying to access a jQuery ID, it is coming back as undefined even though the

I'm attempting to obtain the ID of a specific element, save it as a variable, and then utilize that ID value to interact with other elements in the same section bearing the identical ID. <div class="mainContent"> <div class="articleContent"& ...

The OK Button Dialogbox is currently malfunctioning

While using jQuery for a dialog box, I encountered an issue when trying to delete an element within it. After clicking the ok button, the dialog box did not redirect or close itself properly. The initial content in the dialog box seems to work fine. < ...

Unexpected issue with Typo3 v9 - receiving empty Ajax Plugin JSON response

Consider the following setup in TYPO3 for an ajax request: ajaxAutocomplte_page = PAGE ajaxAutocomplte_page { typeNum = 111871 10 = COA_INT 10 { userFunc = TYPO3\CMS\Extbase\Core\Bootstrap->run extensionNa ...

SQL retrieve data sorted by result column and return it as an array

Wondering if it's possible to retrieve groups as an associative array using SQL. I'm interested in understanding the capabilities of SQL and its potential for solving this particular issue. The challenge at hand involves a database containing a ...

Creating an AJAX request in Play 2.x by using a shared button

Although I have successfully utilized AJAX requests in the past using a form and adding return false to prevent page refresh, I recently encountered an issue when moving my JavaScript into a separate file. The @ commands now fail, making it difficult for m ...

Determining the Size and Color of Squares in a Treemap Based on Content with D3.js

I encountered an issue with a treemap visualization. I came across an example that is similar to my situation, which can be viewed here: In the demo, you can see that the size of each square in the treemap is determined by the content size. However, all s ...

The image zoom function is malfunctioning when trying to adjust the image position

Having some trouble with a code for image zoom in/out. When I adjust the position of the image by applying margin left to either the image or the image container (#view), it affects the zoom functionality - causing the image to move to the left during zoom ...

Starting a tab just once

I have successfully created 4 static HTML pages that include: Home About Services Contact Each page contains a link that leads to another static page named myVideo.html, which plays a video about me in a new tab. The link is available on every page so ...

Unleashing the Potential: Unraveling the Secrets of Deploying a Raffle Ticket System

I am currently developing an innovative android app that incorporates a thrilling raffling system. To ensure user security and authentication, individuals are required to log in via Google OAUTH. After successfully logging in, users must perform specific a ...

What could be causing the issue of not being able to access an element visible in AngularJS Videogular?

I am currently working on integrating the videogular-subtitle-plugin with the most recent version of Videogular/AngularJS. As a newcomer to AngularJS, I believe there must be a simple solution that I am overlooking. My main challenge lies within a directi ...

Obtaining values from a jQuery slider for the price range

<meta charset="utf-8"> <title>jQuery UI Slider - Range slider</title> <link rel="stylesheet" href="jquery.ui.all.css"> <script src="jquery-1.7.1.js"></script> <script src="jquery.ui.widget.js">< ...

Updating a Rails form with a dynamically changing belongs_to select field

My Rails3 app has a Site model, connected to a Region model which belongs to a Country. Currently, the site form includes a select field for Region filled from the Region model. However, I want users to update this list dynamically. I attempted to create ...

Leveraging the Content-Length Header in Scrapy Requests

This is the specific page I am attempting to crawl, and this is the corresponding AJAX request that fetches the necessary data. I have replicated the same AJAX request with identical headers and request payload. While the request does not error out, it re ...