Search code examples
phpjqueryajaxphpmailer

Ajax doesn't send form data to my PHP file to send mail


I'm trying to make a contact form using Ajax and PHPMailer.

I already managed to send a mail with my html form and my php file; however, I'd like to use Ajax to prevent the page from reloading and display a popup telling the user if the mail was sent or not. When I try to submit the form, nothing happens and when I remove the event parameter in my JQuery function, the page loads forever.

I tried displaying the popup without including Ajax in my js file and it worked fine, so I assume the JQuery libraries are imported correctly and the problem is that Ajax doesn't send my from data to my php file.

My HTML form:

<form id="contact" method="post" action="traitement-formulaire.php">
                <div class="form-group">
                  <div class="form-row">
                    <div class="col">
                      <label for="formGroupExampleInput">Nom</label>
                      <input type="text" name="nom" class="form-control" placeholder="Votre nom" id="nom">
                    </div>
                    <div class="col">
                      <label for="formGroupExampleInput2">Prénom</label>
                      <input type="text" name="prenom" class="form-control" placeholder="Votre prénom" id="prenom">
                    </div>
                  </div>
                </div>
                <div class="form-group">
                  <label for="formGroupExampleInput2">Adresse mail</label>
                  <input type="text" name="mail" class="form-control" id=" mail formGroupExampleInput2" placeholder="ex.: [email protected]">
                </div>
                <div class="form-group">
                  <label for="formGroupExampleInput2">Sujet</label>
                  <input type="text" name="sujet" class="form-control" id=" sujet formGroupExampleInput2" placeholder="Objet de votre demande">
                </div>
                <div class="form-group">
                  <label for="formGroupExampleInput2">Votre message</label>
                  <textarea type="text" name="message" class="form-control" id=" message formGroupExampleInput2" placeholder="Détaillez votre demande ici..."></textarea>
                </div>
                <div class="form-group form-actions">
                  <button class="submit-form btn btn-primary btn-block btn-lg" name="submit" type="submit" value="submit">Envoyer</button>
                </div>
              </form>

My JQuery file:

$(document).ready(function(){
$('#contact').submit(function(e){
    e.preventDefault();
    $.ajax({
        dataType: 'JSON',
        url: 'traitement-formulaire.php',
        type: 'POST',
        data: $('#contact').serialize(),
        success: function(data) {
            $('.alert-success').css('display', 'block');
            setTimeout(function(){
                $('.alert-success').css('display' , 'none');
                $('#nom').val("");
                $('#prenom').val("");
                $('#mail').val("");
                $('sujet').val("");
                $('#message').val("")
            }, 3000);
        },
        error: function(data) {
            $('.alert-danger').css('display', 'block');
            setTimeout(function(){
                $('.alert-danger').css('display' , 'none');
                $('#nom').val("");
                $('#prenom').val("");
                $('#mail').val("");
                $('#sujet').val("");
                $('#message').val("")
            }, 3000);
        }
    });
});

});

My PHP file:

<?php
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

require 'PHPMailer/src/Exception.php';
require 'PHPMailer/src/PHPMailer.php';
require 'PHPMailer/src/SMTP.php';

$nom = trim($_POST['nom']);
$prenom = trim($_POST['prenom']);
$mail = trim($_POST['mail']);
$sujet = trim($_POST['sujet']);
$message = trim($_POST['message']);

// Instantiation and passing `true` enables exceptions
$mail = new PHPMailer(true);

try {
    //Server settings
    $mail->SMTPDebug = 0;                                       // Enable verbose debug output
    $mail->isSMTP();                                            // Set mailer to use SMTP
    $mail->Host       = 'ns0.ovh.net';  // Specify main and backup SMTP servers
    $mail->SMTPAuth   = true;                                   // Enable SMTP authentication
    $mail->Username   = '[email protected]';                     // SMTP username
    $mail->Password   = '*************';                               // SMTP password
    $mail->SMTPSecure = 'ssl';                                  // Enable TLS encryption, `ssl` also accepted
    $mail->Port       = 465;                                    // TCP port to connect to

    //Recipients
    $mail->setFrom($mail, $nom);
    $mail->addAddress('[email protected]');     // Add a recipient
    //$mail->addAddress('[email protected]');               // Name is optional
    //$mail->addReplyTo('[email protected]', 'Information');
    //$mail->addCC('[email protected]');
    //$mail->addBCC('[email protected]');

    // Attachments
    //$mail->addAttachment('/var/tmp/file.tar.gz');         // Add attachments
    //$mail->addAttachment('/tmp/image.jpg', 'new.jpg');    // Optional name

    // Content
    $mail->isHTML(true);                                  // Set email format to HTML
    $mail->Subject = $sujet;
    $mail->Body    = $message;
    //$mail->AltBody = 'This is the body in plain text for non-HTML mail clients';

    $mail->send();
    header( 'Location: index.html' );
} catch (Exception $e) {
    echo "Message could not be sent. Mailer Error: {$mail->ErrorInfo}";
}

?>

Thanks for your help!

Edit:

HTML Code for popups:

  <!--Alert-->
  <div class="alert alert-success" role="alert" id="popup-success">
      Votre message a bien été envoyé.
  </div>
  <div class="alert alert-danger" role="alert" id="popup-error">
      Erreur: Votre message n'a pas pu être envoyé.
  </div>
  <!--Alert-->

CSS code for popups:

#popup-success{
display: none;
}
#popup-error{
    display: none;
}

Solution

  • Adding an answer so people who may have the same problems shouldn't look through the comments.

    You first problem was that you where either using slim jQuery or you had jQuery to load after your script.

    Then the paths to you PHPMailer files was wrong.

    Lastly you read the mail from the form and add it to $mail variable

    $mail = trim($_POST['mail']);

    but then you initiallize the PHPMailer object on the same variable

    $mail = new PHPMailer(true);

    Change

    $mail = trim($_POST['mail']);

    to something like

    $sender = trim($_POST['mail']);

    and also change this line

    $mail->setFrom($mail, $nom);

    to

    $mail->setFrom($sender, $nom);

    Finally you have dataType: 'JSON', but your script doesn't respond with a JSON

    You should change that to dataType: 'text', and add echo "mail sent"; after $mail->send();

    Also remove header( 'Location: index.html' ); as it doesn't do something.