How do I get this AJAX form to function properly

Hi all, when I click on the send message button in this AJAX form, it displays both the success and fail messages in the success div class only, how do I configure it to display the success and fail functions in their respective div class. Thank you

Here is the HTML

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Ajax Contact Form</title>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css">
</head>
<body>

    <!-- ajax contact form -->
    <section style="margin-top: 50px;">
        <div class="container">
            <div class="row justify-content-center">
                <div class="col-md-8">
                    <div class="card">
                        <h5 class="card-header">Ajax Contact Form</h5>
                        <div class="card-body">
                            <form class="contact__form" method="post" action="mail.php">
                                
                                <!-- form message -->
                                <div class="row">
                                    <div class="col-12">
                                        <div class="alert alert-success contact__msg" style="display: none" role="alert">
                                            Your message was sent successfully.
                                        </div>
                                    </div>
                                </div>
                                <!-- end message -->

                                <!-- form element -->
                                <div class="row">
                                    <div class="col-md-6 form-group">
                                        <input name="name" type="text" class="form-control" placeholder="Name" required>
                                    </div>
                                    <div class="col-md-6 form-group">
                                        <input name="email" type="email" class="form-control" placeholder="Email" required>
                                    </div>
                                    <div class="col-md-6 form-group">
                                        <input name="phone" type="text" class="form-control" placeholder="Phone" required>
                                    </div>
                                    <div class="col-md-6 form-group">
                                        <input name="subject" type="text" class="form-control" placeholder="Subject" required>
                                    </div>
                                    <div class="col-12 form-group">
                                        <textarea name="message" class="form-control" rows="3" placeholder="Message" required></textarea>
                                    </div>
                                    <div class="col-12">
                                        <input name="submit" type="submit" class="btn btn-success" value="Send Message">
                                    </div>
                                </div>
                                <!-- end form element -->
                            </form>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </section>
    <script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
    <script src="main.js"></script>
</body>
</html>

And this is the JavaScript


(function ($) {
    'use strict';

    var form = $('.contact__form'),
        message = $('.contact__msg'),
        form_data;

    // Success function
    function done_func(response) {
        message.fadeIn().removeClass('alert-danger').addClass('alert-success');
        message.text(response);
        setTimeout(function () {
            message.fadeOut();
        }, 2000);
        form.find('input:not([type="submit"]), textarea').val('');
    }

    // fail function
    function fail_func(data) {
        message.fadeIn().removeClass('alert-success').addClass('alert-success');
        message.text(data.responseText);
        setTimeout(function () {
            message.fadeOut();
        }, 2000);
    }
    
    form.submit(function (e) {
        e.preventDefault();
        form_data = $(this).serialize();
        $.ajax({
            type: 'POST',
            url: form.attr('action'),
            data: form_data
        })
        .done(done_func)
        .fail(fail_func);
    });
    
})(jQuery);

And here is the PHP

<?php

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

        # FIX: Replace this email with recipient email
        $mail_to = "demo@gmail.com";
        
        # Sender Data
        $subject = trim($_POST["subject"]);
        $name = str_replace(array("\r","\n"),array(" "," ") , strip_tags(trim($_POST["name"])));
        $email = filter_var(trim($_POST["email"]), FILTER_SANITIZE_EMAIL);
        $phone = trim($_POST["phone"]);
        $message = trim($_POST["message"]);
        
        if ( empty($name) OR !filter_var($email, FILTER_VALIDATE_EMAIL) OR empty($phone) OR empty($subject) OR empty($message)) {
            # Set a 400 (bad request) response code and exit.
            http_response_code(400);
            echo "Please complete the form and try again.";
            exit;
        }
        
        # Mail Content
        $content = "Name: $name\n";
        $content .= "Email: $email\n\n";
        $content .= "Phone: $phone\n";
        $content .= "Message:\n$message\n";

        # email headers.
        $headers = "From: $name <$email>";

        # Send the email.
        $success = mail($mail_to, $subject, $content, $headers);
        if ($success) {
            # Set a 200 (okay) response code.
            http_response_code(200);
            echo "Thank You! Your message has been sent.";
        } else {
            # Set a 500 (internal server error) response code.
            http_response_code(500);
            echo "Oops! Something went wrong, we couldn't send your message.";
        }

    } else {
        # Not a POST request, set a 403 (forbidden) response code.
        http_response_code(403);
        echo "There was a problem with your submission, please try again.";
    }

?>

fail_func is removing alert-success and adding it back in? Shouldn’t it add alert-danger instead?

 function done_func(response) {
        message.fadeIn().removeClass('alert-danger').addClass('alert-success');

 function fail_func(data) {
        message.fadeIn().removeClass('alert-success').addClass('alert-success');

        

Thank you, when I write it this way and click the send message button, both the success and fail div tags are both displayed on the page at the same time

function fail_func(data) {
        message.fadeIn().removeClass('alert-success').addClass('alert-danger');
        message.text(data.responseText);
        setTimeout(function () {
            message.fadeOut();
        }, 2000);
    }

<div class="row">
   <div class="col-12">
      <div class="alert alert-success contact__msg" style="display: none" role="alert">
         Your message was sent successfully.
      </div>
      <div class="alert alert-danger contact__msg" style="display: none" role="alert">
         There was an error sending your message.
      </div>
   </div>
</div>

Does your code have two contact__msg classes or one? Your sample code has one…

                                <!-- form message -->
                                <div class="row">
                                    <div class="col-12">
                                        <div class="alert alert-success contact__msg" style="display: none" role="alert">
                                            Your message was sent successfully.
                                        </div>
                                    </div>
                                </div>
                                <!-- end message -->

But your last post has two…

<div class="row">
   <div class="col-12">
      <div class="alert alert-success contact__msg" style="display: none" role="alert">
         Your message was sent successfully.
      </div>
      <div class="alert alert-danger contact__msg" style="display: none" role="alert">
         There was an error sending your message.
      </div>
   </div>
</div>

If there are two, your code is going grab them both…

    var form = $('.contact__form'),
        message = $('.contact__msg'),
        form_data;

Thank you Team Leader, my code has two contact__msg classes and the sample code has one. When I write it this way, with one class in the HTML I get the same message for a success or fail. How do I get different messages for success and fail without writing the contact__msg class two times


function fail_func(data) {
        message.fadeIn().removeClass('alert-success').addClass('alert-danger');

<div class="row">
   <div class="col-12">
      <div class="alert alert-success contact__msg" style="display: none" role="alert">
         Your message was sent successfully.
      </div>
   </div>
</div>

But the reason you’re seeing both is because your assignment variable grabs BOTH since they both have a class of contact__msg

To resolve it, you could do a couple things:

  • remove the style=“display:none” from both of the message lines and add a class of d-none, which is the bootstrap equivalent.
  • Remove the assignment of the message variable
  • change the remove class lines to grab the equivalent element and remove the d-none.

so you’d have something like (not tested, so there may (probably) be typos/errors)…

HTML:
<div class="row">
   <div class="col-12">
      <div class="alert alert-success contact__msg d-none" role="alert">
         Your message was sent successfully.
      </div>
      <div class="alert alert-danger contact__msg d-none" role="alert">
         There was an error sending your message.
      </div>
   </div>
</div>

JS:
    var form = $('.contact__form'),
        form_data;

    function done_func(response) {
         $('.alert-success').removeClass('d-none').html(response);    // remove the d-none class so it's shown and set the text (.text() is a getter only) 

    function fail_func(data) {
         $('.alert-danger').removeClass('d-none').html(data.responseText);    // remove the d-none class so it's shown and set the text (.text() is a getter only) 

That SHOULD resolve it. If you’re still seeing both messages, then there’s something else which is setting them to visible.

Just a thought and as I never use any libraries I have no idea how their request/response code works, but could it be that you are receiving more than one response back, one ok and the others fail. It would explain your symptoms.
But I may be completely wrong.

Thank you Team Leader, the Javascript works and is cleaner.
I’ve tested the form in many ways and have gotten a variety of different results.
How is the form going to display only the success or error message from the HTML . Sometimes the form displays plain text from the mail.php page and due it’s AJAX nature its meant to be a one page development


(function ($) {
    'use strict';

    var form = $('.contact__form'), form_data;

    // Success function
    function done_func(response) {
        $('.alert-success').removeClass('d-none') .html(response) ; // remove the d-none class so it's shown and set the text (.text() is a getter only) 
    }

    // fail function
    function fail_func(data) {
         $('.alert-danger').removeClass('d-none') .html(data.responseText) ; // remove the d-none class so it's shown and set the text (.text() is a getter only) 
    }
    
    form.submit(function (e) {
        e.preventDefault();
        form_data = $(this).serialize();
        $.ajax({
            type: 'POST',
            url: form.attr('action'),
            data: form_data
        })
        .done(done_func)
        .fail(fail_func);
    });
    
})(jQuery);

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.