Home » Jquery » php – Sending email in WordPress using jQuery and ajax

php – Sending email in WordPress using jQuery and ajax

Posted by: admin February 22, 2020 Leave a comment

Questions:

I have a little problem here. I’m working on a simple quotation form on wordpress.
I have two forms, the first one sends data to jQuery that does all the calcs (very few options so we didn’t use a DB), then prints an html row. No issue until here; the problems start when I’m trying to send that row/rows to PHP to send a simple email. I’ve tried with ajax and wp_mail but with no success.
Here is what i’ve tried:

HTML inside wordpress template file:

<!--first form with data to calculate-->
 <form class="needs-validation">
  <!--select fields, no problem here-->
 </form>
  <div class="table-responsive"> <!--risultato preventivo-->
            <table class="table table-bordered" id="dynamic_field">
                <tr>
                    <!--result given by jQuery-->
                </tr>
            </table>
   <p id="total"><!--total price passed by jQuery--></p>
   </div>

   <!--second form for sending email-->
   <form action="#" method="POST">
            Nome:<br>
            <input type="text" name="nome" id="nome">
            <br>
            Cognome:<br>
            <input type="text" name="cognome" id="cognome">
            <br>
            Email:<br>
            <input type="email" name="email" id="email">
            <input type="hidden" name="invia" value="s">
            <input type="submit" id="inviaForm" value="Invia">
        </form>
        <div id="worked"></div>

jQuery with calcs inside file main.js:

(function ($) {
   $(document).ready(function () {

      function generaRisultato (riga,nProfilo,nColore,nSerramento,costoRiga){
        var risultato = '<tr id="row' + riga +
         '" class="dynamic-added"><td><div><h5 class="my-0">Articolo: ' + nProfilo +
         '</h5><br><small class="text-muted">Colorazione: ' + nColore +
         '</small><br><small class="text-muted">Serramento: ' + nSerramento +
         '</small></div><span id="costo-riga'+riga+'">'+costoRiga+'€</span></td>'+
         '<td><button type="button" name="remove" id="'+ riga +'" class="btn btn_remove">-</button> 
         </td></tr>';
        return risultato;    
       }
        //calcs done correctly
        $('#dynamic_field').append(generaRisultato(i,profile,color,name,price)); //result printed

       var risultatoFinale = $('#dynamic_field').html(); //variable with result stored for email


       //sending form mail ajax
    $('#inviaForm').on('submit', function(e){
    //evito l'invio del form
    e.preventDefault(); 

    //recupero i valori
    var nomeUser = $('#nome').val();
    var cognomeUser = $('#cognome').val();
    var emailUser = $('#email').val();
    var totaleFinale = $('#totale').html();
    var preventivoFinale = $('#dynamic_field').html();

    //eseguo la chiamata ajax
    $.ajax({
      type: "POST",
      url: my_vars.ajaxurl, 
      data: {
        action : 'invio_mail', //azione da eseguire
        _nonce : my_vars.nonce,
        nome : nomeUser,
        cognome : cognomeUser,
        email : emailUser,
        totale : totaleFinale,
        preventivo : preventivoFinale
      },
      success: function(res){
        $('#funzionante').html(res);
      }
    });
  });

   });
 })(jQuery);

PHP inside functions.php:

function vf_load_theme_preventivatore(){
wp_register_script('main', get_template_directory_uri().'/preventivatore/js/main.js', false, false, 
true);
wp_enqueue_script('main');

wp_localize_script( 'main', 'my_vars', array(
    'ajaxurl' =>admin_url('admin-ajax.php'),
    'nonce' => wp_create_nonce('invio-mail-nonce')
));
}
add_action('wp_enqueue_scripts', 'vf_load_theme_preventivatore');

function invio_mail_ajax(){
//verifico che il nonce sia corretto
if(!wp_verify_nonce( $_REQUEST['_nonce'], 'invio-mail-nonce') ){
    die('Non autorizzato!');
}

//Prepariamo le variabili da usare
$successo = '';
$nome = strval($_REQUEST['nome']);
$cognome = strval($_REQUEST['cognome']);
$email = $_REQUEST['email'];
$preventivo = $_REQUEST['preventivo'];
$totale = $_REQUEST['totale'];

//script mail
$header = "From: Site <[email protected]>\n";
$header .= "BCC: Altro Ricevente <[email protected]>\n";
// costruiamo le intestazioni specifiche per il formato HTML
$header .= "Content-Type: text/html; charset=\"UTF-8\"\n";
$oggetto = "Ecco il tuo preventivo";
$messaggio = "<html><body><p>Richiesta preventivo da sito</p><p>Nome: ".$nome."</p><p>Cognome: 
 ".$cognome."</p><p>Email: ".$email."</p> <p>Dati del preventivo</p><p>".$preventivo."</p><p>Totale: 
 ".$totale."€</p></body></html>";
$inviata = wp_mail($email,$oggetto,$messaggio,$header);

$successo .= '<p>'.$nome.'</p>';

echo $successo;

die();

if($inviata){
    $successo = '<p> email invata</p>';
    echo $successo;
    die();
 } else die('errore nella mail');
}
add_action('wp_ajax_invio_mail','invio_mail_ajax');
add_action('wp_ajax_nopriv_invio_mail','invio_mail_ajax');

That’s what i’ve done, i’ve simply hidden the jQuery calculations because that worked flawlessly.
I wanted to send an email with an html formatted text, with this solution the email doesn’t even get sent (before putting ajax and php script in fuction the email arrives, php was inside the template file), also i cannot pass the html table rows with results and the total of the quotation. Maybe i got wrong the ajax or php part.
Is there any help about this? thank you for all your support!

How to&Answer:

Created AJAX submit form. Tested working good you can change your data. Hope this help you.

Copy and paste in your function.php file

        function.php

        function invio_mail(){
        $to = '[email protected]';
        $subject = 'The subject';
        $body = 'The email body content';
        $headers = array('Content-Type: text/html; charset=UTF-8');

        wp_mail( $to, $subject, $body, $headers );
echo 'mail send';
            die;
        }
        add_action("wp_ajax_invio_mail", "invio_mail");
        add_action("wp_ajax_nopriv_invio_mail", "invio_mail");


        Just paste you want the page (Form)

        <form id="ajaxformid" action="#" method="POST">
                Nome:<br>
                <input type="text" name="nome" id="nome">
                <br>
                Cognome:<br>
                <input type="text" name="cognome" id="cognome">
                <br>
                Email:<br>
                <input type="email" name="email" id="email">
                <input type="hidden" name="invia" value="s">
                <input type="submit" id="inviaForm" value="Invia">
        </form>

        Just paste in footer
        <script>
         jQuery(document).ready(function($) {   
            var frm = $('#ajaxformid');
            frm.submit(function (e) {
                var formData = {
                    nome: jQuery('#nome').val(),
                    cognome: jQuery('#cognome').val(),
                    email: jQuery('#email').val(),
                    action:'invio_mail'
                };
                $.ajax({
                    type        : 'POST', 
                    url         : "<?php echo admin_url('admin-ajax.php'); ?>",
                    data        : formData,
                    dataType    : 'json',
                    encode          : true
                }).done(function(data) {
                    console.log(data);        
                }).fail(function(data) {
                    console.log(data);

                });
                e.preventDefault();     
            });

          });
        </script>