Submit silent in form

0

I have a problem with my form. The functionality of sending information to an email is good thanks to PHPMailer , when you submit, the information is sent to a php file called contacto.php, this is where I check that it is not spam and I think the mail to finally send it to my account. When all the logic of the program ends, by means of a header I return to the initial page, causing it to load again. That last is what I want to avoid. I would like the submit to be done, and once sent, the user remains positioned on the form.

I leave the code of the php file where the logic of sending information by mail is. The action of the form points to here:

<?php
// Import PHPMailer classes into the global namespace
// These must be at the top of your script, not inside a function
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

require 'vendor/autoload.php';
if(isset($_POST['enviar'])) {
    if ($_POST['no-spam'] != ''){
        exit();
    }else {
        if (isset($_POST['name'], $_POST['email'], $_POST['comments'])){
            $mail = new PHPMailer(true);                              
            try {
                //Server settings
                $mail->SMTPDebug = 3;                                
                $mail->isSMTP();                         
                $mail->Host = '';
                $mail->SMTPAuth = true;                  
                $mail->Username = '';      
                $mail->Password = '';         
                $mail->SMTPSecure = 'ssl';                           
                $mail->Port = 465;                                   
                $mail->SMTPOptions = array('ssl' => array( 'verify_peer' => false, 'verify_peer_name' => false, 'allow_self_signed' => true ));
                //Recipients
                $mail->setFrom('', 'Formulario de contacto');
                $mail->addAddress('');     

                //Content
                $mail->isHTML(false);                         
                $mail->Subject = 'Cliente: '.$_POST['email'];
                $mail->Body    = $_POST['comments'];
                $mail->AltBody = $_POST['comments'];;

                $mail->send();
                header('Location: ../index_en.html');

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

}

}

Quito personal code data by privacy.

    
asked by Pelayo 13.09.2018 в 11:55
source

1 answer

1

As you have been told in the comments, you basically have your form. It is not necessary to put an action or type.

To the event submit you declare a listener, and your handler is a function that sends the ajax but returns false (the form is not sent as is traditional)

The following snippet will not work because there is no send_email.php listening behind. But it illustrates how you should put it on your front.

jQuery(document).ready(function() {
  jQuery('#formulario').on('submit', function() {

    $.ajax({
      type: 'POST',
      dataType: 'json',
      url: 'send_email.php',
      data: jQuery(this).serialize()
    }).then(function(res) {
      console.log(res);
    }).catch(function(err) {
      console.warn(err);
    });

    return false;
  });
});
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>


<div class="container-fluid">
  <form id="formulario" class="form-horizontal">
    <div class="form-group">
      <label for="nombre" class="col-xs-2 control-label">Nombre</label>
      <div class="col-xs-10">
        <input type="nombre" name="name" class="form-control" id="nombre" placeholder="ej John Doe">
      </div>
    </div>
    <div class="form-group">
      <label for="email" class="col-xs-2 control-label">Email</label>
      <div class="col-xs-10">
        <input type="email" class="form-control" name="email" id="email" placeholder="ej [email protected]">
      </div>
    </div>
    <div class="form-group">
      <label for="comment" class="col-xs-2 control-label">Comentario</label>
      <div class="col-xs-10">
        <textarea class="form-control" style="height:50px;" name="comment" id="comment" placeholder="Ponga un comentario"></textarea>
      </div>
    </div>

    <div class="form-group">
      <div class="col-xs-offset-2 col-xs-6">
        <div class="checkbox">
          <label>
             <input type="checkbox" name="no-spam"> Le prometo que no es spam
          </label>
        </div>
      </div>
      <div class="col-xs-4">
        <button type="submit" class="btn btn-default pull-right">Enviar</button>
      </div>
    </div>

  </form>
</div>

In the backend, the flow should be:

<?php
// según yo, el autoload debe ir primero para que funcione "use PHPMailer\..." pero si te funciona...
require 'vendor/autoload.php';

use PHPMailer\PHPMailer\Exception;
use PHPMailer\PHPMailer\PHPMailer;

// esto lo puedes dar por subentendido
// if(isset($_POST['enviar']))

function sendEmail()
{
    if (!isset($_POST['no-spam']) || $_POST['no-spam'] != '') {
        return ['status' => 'error', 'msg' => 'parece que es spam'];

    }
    if (!(isset($_POST['name'], $_POST['email'], $_POST['comments']))) {
        return ['status' => 'error', 'msg' => 'complete todos los campos'];
    }

    $mail = new PHPMailer(true);
    try {
        //Server settings
        $mail->SMTPDebug = 3;
        $mail->isSMTP();
        $mail->Host        = '';
        $mail->SMTPAuth    = true;
        $mail->Username    = '';
        $mail->Password    = '';
        $mail->SMTPSecure  = 'ssl';
        $mail->Port        = 465;
        $mail->SMTPOptions = ['ssl' => ['verify_peer' => false, 'verify_peer_name' => false, 'allow_self_signed' => true]];
        //Recipients
        $mail->setFrom('', 'Formulario de contacto');
        $mail->addAddress('');

        //Content
        $mail->isHTML(false);
        $mail->Subject = 'Cliente: ' . $_POST['email'];
        $mail->Body    = $_POST['comments'];
        $mail->AltBody = $_POST['comments'];

        $mail->send();
        return ['status' => 'OK', 'msg' => 'mail enviado'];

    } catch (Exception $e) {
        return ['status' => 'error', 'msg' => '$mail->ErrorInfo'];
    }

}

echo json_encode(sendEmail());

So, in the function sent by the ajax, the response brings a status field that tells you if there was an error or everything went well. Depending on that you show the message.

    
answered by 13.09.2018 / 13:17
source