Jump to content

AJAX contact form not working


Nic727

Recommended Posts

Hi,

 

I followed this tutorial to make contact form working without going physically to the php page.

 

http://blog.teamtreehouse.com/create-ajax-contact-form

 

The thing is that this code is not working. I tried on my website with my own contact form and with this code only. Both of them don't work.

 

Here is my full code for my website :

 

HTML

<div id="form-messages"></div>
     
    <form id="ajax-contact" name="email" method="post" action="contact.php">
                <p>Les champs sont obligatoires*</p>
                 
            <div class="rowform"> 
                <div class="half gauche"> 
                    <label>Prénom*</label>
                    <input name="prenom" id="prenom" type="text" required>
                </div>
                  
                <div class="half droite"> 
                    <label>Nom*</label>
                    <input name="nom" id="nom" type="text" required>
                </div>
            </div>
                 
            <div class="rowform">
                <div class="half gauche">
                    <label>Courriel*</label>
                    <input name="courriel" id="courriel" type="email" required>
                </div>    
              
                <div class="half droite"> 
                    <label>Téléphone</label>
                    <input name="phone" id="phone" type="number">
                </div>    
            </div>
         
            <div class="rowform"> 
                <label>Sujet*</label>
                <input name="sujet" id="sujet" type="text" required>
            </div>
                 
            <div class="rowform"> 
                <label>Votre message*</label>
                <textarea name="message" required></textarea>
            </div>
                <div class="end-form">    
                    <button id="submit" class="submit" name="submit" type="submit" value="envoyer"><i class="fa fa-paper-plane" aria-hidden="true"></i> Envoyer</button>
                </div>    
            </form>

JS

if ($_SERVER["REQUEST_METHOD"] == "POST") {
        // Get the form fields and remove whitespace.
        $prenom = strip_tags(trim($_POST["prenom"])); //Obligatoire
        $nom = strip_tags(trim($_POST["nom"])); //Obligatoire
        $courriel = filter_var(trim($_POST["courriel"]), FILTER_SANITIZE_EMAIL);//Obligatoire
        $phone = strip_tags(trim($_POST["phone"]));
        $suj = strip_tags(trim($_POST["sujet"])); //Obligatoire
        $nom = str_replace(array("\r","\n"),array(" "," "),$nom);
        $message = trim($_POST["message"]); //Obligatoire
 
        // Check that data was sent to the mailer.
        if (empty($prenom) OR empty($nom) OR empty($courriel) OR empty($sujet) OR empty($message) OR !filter_var($courriel, FILTER_VALIDATE_EMAIL)) {
            // Set a 400 (bad request) response code and exit.
            http_response_code(400);
            echo "Oops! There was a problem with your submission. Please complete the form and try again.";
            exit;
        }
 
        // Set the recipient email address.
        // FIXME: Update this to your desired email address.
        $destinataire = "contact@nicolas-duclos.com"; //to or recipient
 
        // Set the email subject.
        $sujet = $suj; //Obligatoire
 
        // Build the email content. (Corps du message)
        $email_content = "Prenom : $prenom \r\n";
        $email_content .= "Nom : $nom \r\n";
        $email_content .= "Courriel : $courriel \r\n";
        $email_content .= "Telephone : $phone \r\n";
        $email_content .= "Sujet : $sujet \r\n";
        $email_content .= "Message :\r\n \r\n $message \r\n";
     
        // Build the email headers.
        $semi_rand = md5(time());
        $mime_boundary = "==Multipart_Boundary_x{$semi_rand}x";
        $headers = 'From :' .$prenom.' ' .$nom.'<' .$courriel. "> \r\n";
        $headers .= 'Reply-To : '.$courriel."\r\n";
        $headers .= "Content-type: text/plain; charset=UTF-8"."\r\n";
 
        mail($destinataire,$sujet,$email_content,$headers);
 
        // Send the email.
        if (mail($destinataire,$sujet,$email_content,$headers)) {
            // 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 and 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.";
    }

PHP

$(function() {
    // Get the form.
    var form = $('#ajax-contact');
 
    // Get the messages div.
    var formMessages = $('#form-messages');
 
    // TODO: The rest of the code will go here...
});
// Set up an event listener for the contact form.
$(form).submit(function(event) {
    // Stop the browser from submitting the form.
    event.preventDefault();
 
    // TODO
    // Serialize the form data.
    var formData = $(form).serialize();
 
    // Submit the form using AJAX.
    $.ajax({
        type: 'POST',
        url: $(form).attr('action'),
        data: formData,
        success: function(response) {
            // Make sure that the formMessages div has the 'success' class.
            $(formMessages).removeClass('error');
            $(formMessages).addClass('success');
 
            // Set the message text.
            $(formMessages).text(response);
 
            // Clear the form.
            $('#prenom').val('');
            $('#nom').val('');
            $('#courriel').val('');
            $('#phone').val('');
            $('#sujet').val('');
            $('#message').val('');
        },
        error: function(data) {
            // Make sure that the formMessages div has the 'error' class.
            $(formMessages).removeClass('success');
            $(formMessages).addClass('error');
 
            // Set the message text.
            if (data.responseText !== '') {
                $(formMessages).text(data.responseText);
            } else {
                $(formMessages).text('Oops! An error occured and your message could not be sent.');
            }
        }
    })
 
});

A lot of thing doesn't work for me.

 

1. It goes to contact.php instead of staying on my HTML page and activating the div "form-messages".

2. The JS code is stopping at "// Check that data was sent to the mailer." so even if my input are not empty, it show (on contact.php unfortunately) the error text.

3. If I put this section under commentary, the mail is sent, but two times instead of one, which is a big issue... Also go on contact.php instead of staying on the current page and show text in "form-messages".

 

 

Thank you for helping me :)

Link to comment
Share on other sites

$(form) is not defined, because you defined it inside an anonymous function, so it's not available outside You should put the event listener inside the anonymous function.

Link to comment
Share on other sites

$(form) is not defined, because you defined it inside an anonymous function, so it's not available outside You should put the event listener inside the anonymous function.

Like what?

 

Instead of :

$(function() {
    // Get the form.
    var form = $('#ajax-contact');
 
    // Get the messages div.
    var formMessages = $('#form-messages');
 
    // TODO: The rest of the code will go here...
});

I should have


    // Get the form.
    var form = $('#ajax-contact');
 
    // Get the messages div.
    var formMessages = $('#form-messages');

only?

Edited by Nic727
Link to comment
Share on other sites

You have a comment that says this:

 

// TODO: The rest of the code will go here...
That's where your additional code should go, not after the function.

 

 

... Still not working. I did remove the first function and only put the variables here, but still go to contact.php with error "Oops! There was a problem with your submission. Please complete the form and try again." instead of staying on HTML page. Doesn't seem to get the AJAX working.

 

EDIT :

 

Nevermind, I just added the second faction into the first one. I can get the text appear on submit. GREAT!

But still have the error... Maybe an error when checking if a field is empty? It doesn't seem like that... Also, why is it sending email two times if I remove this part?

Edited by Nic727
Link to comment
Share on other sites

Look at your browser's developer console, if there is a Javascript error then you'll see the message there. It sounds like it's not attaching the submit event to the form, and you'll be able to look at the error message to see why.

Link to comment
Share on other sites

Also, is it a good idea to add this for form validation (PHP side) as an example :

 

$nom = htmlspecialchars(strip_tags(trim($_POST["nom"])));

 

So in my JS I could have the pattern and validation message showing on my page, but server side I could remove html code....

 

But still trying to figure what's wrong with http404... All my fields are not empty. Don't know why it think there is something wrong in my syntax?

Link to comment
Share on other sites

This empty($sujet) should be empty($suj), $sujet is not defined until later on further down page.

Thank you, it fixed it.

 

Now I need to get it only send one email instead of two...

 

Do you think it's because there is two mail() and need to put the first one into a variable?

mail($destinataire,$sujet,$email_content,$headers);
 
        // Send the email.
        if (mail($destinataire,$sujet,$email_content,$headers)) {
            // 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 and we couldn't send your message.";
        }
EDIT : It worked ;) Edited by Nic727
Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...