Search code examples
javascriptphpformsemailphpmailer

PHPMailer - The attachment is sent but the form is not reset


I have two different files (.pdf) to send based on the selection made by the user. In practice, when the user selects the select 'user', he must send the attachment associated with that selection. By adding the code in the PHP file, the submission occurs but the form is not reset. Am I wrong in doing the file selection? Only the file of array "0" is sent, even if the second select is selected

This is select:

<select name="user" id="user">
 <option disabled selected>Richiesta prestazione per</option>
 <option value="adulti">Adulti</option>
 <option value="minori">Minorenni</option>
</select>

This is PHPMailer:

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

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

// Instantiation and passing [ICODE]true[/ICODE] enables exceptions
$mail = new PHPMailer(true)
  
$name = $_POST['name'];
$surname = $_POST['surname'];
$email = $_REQUEST['email'] ;
$phone = $_POST['phone'];
//$user = $_POST['user']; // i tried to disable this //
$pay = $_POST['pay'];
$message = $_REQUEST['message'];
$cod = mt_rand(100000, 999999);

//replacing them with this
$user = array (0 => './documents/test.pdf', 1 => './documents/test2.pdf');
$file = $user[(int) $_POST['user']];

try {
 //Server settings
 //$mail->SMTPDebug = 2; // Enable verbose debug output
 $mail->isSMTP(); // Set mailer to use SMTP
 $mail->CharSet = 'UTF-8';
 $mail->Host = '_MYMAIL_'; // Specify main and backup SMTP servers
 $mail->SMTPAuth = true; // Enable SMTP authentication
 $mail->Username = '_MYMAIL_'; // SMTP username
 $mail->Password = '_MYPASS_'; // SMTP password
 $mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;
 $mail->Port = 587; // TCP port to connect to

//Recipients
 $mail->setFrom($email, $name);
 $mail->addAddress('_MYMAIL_', '_MYNAME_'); // Add a recipient
 $mail->addReplyTo($email, $name);

// Content
 $mail->isHTML(true); // Set email format to HTML
 $mail->Subject = "\xF0\x9F\x93\x86 Richiesta di Consulenza Online";
 $mail->Body = _MYMESSAGE_;

 if(!$mail->send()) {
    echo 'Message could not be sent.';
    echo 'Mailer Error: ' . $mail->ErrorInfo;
} else {
    echo 'Message sent';
}

$mail->ClearAddresses();
$mail->ClearaddReplyTo();

// Add the admin address
$mail->AddAddress($email);
$mail->setFrom('_MYMAIL_', '_MYNAME_');
$mail->Subject = _MYSUBJECT_;
$mail->addReplyTo('_MYMAIL_', '_MYNAME_');
$mail->AddAttachment($file) **//I add this to attach the .pdf file**
$mail->Body = 

<body>
 
   <h2>Codice prenotazione: '.$cod.'</h2>
 
   <table>
     <thead>
       <tr>
         <th>Nome</th>
         <th>Cognome</th>
         <th>Adulto/Minore</th>
         <th>Pagamento</th>
         <th>Telefono</th>
       </tr>
     </thead>
     <tbody>
       <tr>
         <td>'.$name.'</td>
         <td>'.$surname.'</td>
         <td>'.$user.'</td> //this is line 114
         <td>'.$pay.'</td>
         <td>'.$phone.'</td>
       </tr>
       <tr>
         <td colspan="5">Messaggio:<br><br>'.$message.'</td>
       </tr>
     </tbody>
   </table>
 </body>;

$mail->Send();


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

And this is call Ajax in file .js:

    $("#formBook").submit(function (event) {
    // cancels the form submission
    event.preventDefault();
    submitForm();
  });
  
  function submitForm() {
     //Initiate Variables With Form Content
     var name = $("#name").val();
     var surname = $("#surname").val();
     var email = $("#email").val();
     var phone = $("#phone").val();
     var user = $("#user").val();
     var message = $("#message").val();
     var pay = $("#pay").val();
  
    $.ajax({
      type: "POST",
      url: "email_monia.php",
      data: "name=" + name + "&email=" + email + "&message=" + message + "&user=" + user + "&phone=" + phone + "&pay=" + pay + "&surname=" + surname,
      success: function (data) {
        if (data == 'Message sent') {
          formSuccess();
        }
      }
    });
  }

function formSuccess() {
$("#formBook")[0].reset();
// custom toast
iziToast.show({
  color: 'light',
  icon: 'fas fa-paper-plane',
  message: '<strong>Grazie!</strong></br>Il tuo messaggio è stato inviato',
  messageLineHeight: 20,
  messageSize: 15,
  position: 'center', // bottomRight, bottomLeft, topRight, topLeft, topCenter, bottomCenter
  progressBarColor: '#00909D',
  backgroundColor: ' #9ad3ca',
  titleColor: '#222',
  messageColor: '#222',
  iconColor: '#F7F7F7',
  closa: false,
  displayMode: 'once',
  pauseOnHover: false,
  resetOnHover: false,
});
}

Solution

  • I think you are submitting name in user field instead of index, in that case you should update your attachment array to an associative array

    //replacing them with this
    $user = array ( 
        'adulti' => './documents/test.pdf',
        'minori' => './documents/test.pdf'
    );
    $file = $user[$_POST['user']];
    

    In the formSuccess function

    $("#formBook").reset();
    

    Can you verify your response

    $.ajax({
      type: "POST",
      url: "email_monia.php",
      data: "name=" + name + "&email=" + email + "&message=" + message + "&user=" + user + "&phone=" + phone + "&pay=" + pay + "&surname=" + surname,
      success: function (data) {
        // check response here
        console.log(data);
        if (data == 'Message sent') {
          formSuccess();
        }
      }