Send mail form with AJAX (JavaScript & PHP) doesn't work

I’m new to Stack Overflow.
I’m trying to have a simple e-mail form on my website, so I’ve copied one but can’t get it to work. The "Send" button just doesn’t seem to do anything.
I am not a programmer and know very little about code

A friend told me it’s as if the PHP isn’t recognized.

HTML code

<form id="contact-form" action="" method="POST" class="tm-contact-form">
    <div class="form-group">
        <input type="text" name="name" class="form-control rounded-0" placeholder="Full Name" required />
    </div>
    <div class="form-group">
        <input type="email" name="email" class="form-control rounded-0" placeholder="Email" required />
    </div>
    <div class="form-group">
        <select class="form-control" id="contact-select" name="inquiry">
            <option value="-">Subject</option>
            <option value="3DPrints">3D Prints</option>
            <option value="AmpsEffects">Amps &amp; Effect Pedals</option>
            <option value="Other">Other</option>
        </select>
    </div>
    <div class="form-group">
        <textarea rows="8" style="resize: none;" name="message" class="form-control rounded-0" placeholder="Message" required></textarea>
    </div>
    <div class="form-group mb-4">
        <div id="result-message" class="alert alert-success d-none">Send result message will display here</div>
    </div>
    <div class="form-group tm-text-right">
        <button type="submit" class="tm-btn tm-btn-primary">Send</button>
    </div>
</form>

JS file

$(function () {    
    $("#contact-form").submit(function (e) {
        e.preventDefault();
        var form_data = $(this).serialize(); 
        $.ajax({
            type: "POST", 
            url: "js/call-form.php",
            dataType: "text/json", // Add datatype
            data: form_data
        }).done(function (data) {
            console.log(data);
            alert("It's OK!");
        }).fail(function (data) {
            console.log(data);
            alert("It's not OK!");
        });
    }); 
});

PHP file

if ((isset($_POST['name'])) && (isset($_POST['email'])) && (isset($_POST['inquiry'])) && (isset($_POST['message']))) { 
    $to = 'info@hemmelaudio.com';
    $subject = '.$_POST['inquiry'].';
    $message = '<html>
            <head>
                <title>'.$_POST['inquiry'].'</title>
            </head>
            <body>
                <p><b>From:</b> '.$_POST['name'].'</p>
                <p><b>Email:</b> '.$_POST['email'].'</p><br>
                <p>'.$_POST['message'].'</p>
            </body>
        </html>'; 
  $headers  = "Content-type: text/html; charset=utf-8 \r\n"; 
/* $headers .= "From: Hemmelaudio.com\r\n"; */
mail($to, $subject, $message, $headers);

  echo json_encode(array('status' => 'success'));
} else {
  echo json_encode(array('status' => 'error'));
}

I have put the PHP file with 755 permissions.

Please help!
Thanks

1 thought on “Send mail form with AJAX (JavaScript & PHP) doesn't work”

    • Use FormData API with $.ajax’s processData: false, and contentType: false,
    • Use dataType: "json", not dataType: "test/json",
    • Use $.ajax‘s .always() if you’re gong to define the response status
    • Learn about the benefits of Heredoc
    • Use a proper HTML-email Doctype
    • Use <label> as wrapper.
    • '.$_POST['inquiry'].' ?! Please use a better code editor. It will highlight the errors for you.

    index.html:

    <!DOCTYPE html>
    <html lang="en">
        <head>
            <meta charset="UTF-8" />
            <meta http-equiv="X-UA-Compatible" content="IE=edge" />
            <meta name="viewport" content="width=device-width, initial-scale=1.0" />
            <title>MY PAGE</title>
            <link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet" type="text/css" />
            <style>
                label.form-group {
                    display: block;
                    max-width: none;
                }
                textarea {
                    resize: vertical;
                }
            </style>
        </head>
    
        <body>
            <form id="contact-form" action="" method="POST" class="tm-contact-form">
                <label class="form-group">
                    <span class="control-label col-lg-3">Full name:</span>
                    <input type="text" name="name" class="form-control" placeholder="Full Name" required value="Lorem Ipsum" />
                </label>
    
                <label class="form-group">
                    <span class="control-label col-lg-3">Email:</span>
                    <input type="text" name="email" class="form-control" placeholder="Full Name" required value="text@example.com" />
                </label>
    
                <label class="form-group">
                    <span class="control-label col-lg-3">Subject:</span>
                    <select class="form-control" name="inquiry" required>
                        <option value="3DPrints">3D Prints</option>
                        <option value="AmpsEffects">Amps &amp; Effect Pedals</option>
                        <option value="Other">Other</option>
                    </select>
                </label>
    
                <label class="form-group">
                    <span class="control-label col-lg-3">Message:</span>
                    <textarea name="message" class="form-control" placeholder="Message" required>Test message</textarea>
                </label>
    
                <div id="result-message" class="d-none form-group mb-4 alert alert-primary"></div>
    
                <div class="form-group tm-text-right">
                    <button type="submit" class="tm-btn tm-btn-primary">Send</button>
                </div>
            </form>
    
            <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    
            <script
                src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"
                integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1"
                crossorigin="anonymous"
            ></script>
            <script
                src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"
                integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM"
                crossorigin="anonymous"
            ></script>
            <script src="js/send-email-ajax.js"></script>
        </body>
    </html>
    

    js/send-email-ajax.js

    jQuery(function ($) { // DOM ready and $ alias in scope
    
        const $message = $("#result-message");
    
        $("#contact-form").on("submit", function (e) {
            e.preventDefault();
            const FD = new FormData(this);
    
            $message.text("Sending email...").removeClass("d-none");
    
            $.ajax({
                type: "POST",
                url: "js/call-form.php",
                dataType: "json", // Expected response format
                processData: false,
                contentType: false,
                data: FD,
            })
                .always(function (data) {
                    $message.text(data.message).addClass(data.status === "error" ? "alert-danger" : "alert-success");
                })
                .fail(function (err) {
                    $message.text("!!! Could not send email").addClass("alert-danger");
                });
        });
    
    });
    
    

    js/call-form.php:

    <?php
    
    if (
        isset($_POST['name']) &&
        isset($_POST['email']) &&
        isset($_POST['inquiry']) &&
        isset($_POST['message'])
    ) {
    
        $to = "info@hemmelaudio.com";
        $subject = $_POST['inquiry']; // '.$_POST['inquiry'].'; ?! please, use a better code editor
        $name = $_POST['name'];
        $email = $_POST['email'];
        $message = $_POST['message'];
    
        $html = <<<EX
        <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
        <html xmlns="http://www.w3.org/1999/xhtml" lang="en-GB">
        <head>
            <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
            <title>$subject</title>
            <meta name="viewport" content="width=device-width, initial-scale=1.0"/>
        </head>
        <body>
            <table width="100%" style="border-collapse: collapse;">
                <tbody>
                    <tr><th>From:</th><td>$name</td></tr>
                    <tr><th>Email:</th><td>$email</td></tr>
                    <tr><th>message:</th><td>$message</td></tr>
                </tbody>
            </table>
        </body>
        </html>
    EX; // !! Don't indent this line !!
    
        $headers  = "MIME-Version: 1.0\r\n";
        $headers .= "Content-type: text/html; charset=utf-8\r\n";
        $headers .= "From: Hemmelaudio.com\r\n";
    
        $isSent = mail($to, $subject, $html, $headers);
        echo json_encode([
            "status" => ($isSent ? "success" : "error"),
            "message" => ($isSent ? "Email is sent" : "Email is not sent"),
        ]);
    } else {
        echo json_encode([
            "status" => "error",
            "message" => "Missing fields"
        ]);
    }
    
    exit;
    
    Reply

Leave a Comment