skip to Main Content

I’m not experienced in php/js, but I’m trying to build a custom contact form in WordPress and so far, after following some tutorials and reading a lot of stuff, I managed to make it work out enough to send the content of the form to my email. That part is fine, but I believe I’m missing the validation part, cause I’m still being able to send the messages to my email even if the fields are empty or not filled in the way as it is required. I tried to simpifly the code as much as possible to not keep it too long here, please let me know in case it’s not understandable enough.

<html>
<body>
<div id="successmail" style="display:none">MESSAGE SENT</div>
<div id="errormail" style="display:none">MESSAGE NOT SENT</div>
    
 <form id="enquiry" method="post" name="enquiry">
  <div class="form">
   <input type="text" class="fname" name="fname" placeholder="" pattern="[a-zA-Z]{1,36}" required> 
   <label for="namef">Your name</label>
  </div>
  <div class="form">
   <input type="text" class="lname" name="lname" placeholder="" pattern="[a-zA-Z]{1,36}" required> 
   <label for="lname">Your surname</label>
  </div>
  <div class="form">
   <input type="email" class="email" name="email" placeholder="" pattern="[^@s]+@[^@s]+.[^@s]+" required > 
   <label for="email">Your email</label>
  </div>
  <div class="form">
   <select class="select" name="title" required>
     <option>Option 1</option>
     <option>Option 2</option>
     <option>Option 3</option>
   </select>
  </div>
  <div class="form2">
   <textarea class="message" name="message" placeholder="" required></textarea> 
   <label for="tellme">Your message</label>
   </div>
  <div class="contactbutton">
    <button class="button" role="button" type="submit">SEND</button>
  </div>
</form>
    
<script>
(function($){

 $('#enquiry').submit( function(event){

                event.preventDefault();

                var endpoint = '<?php echo admin_url('admin-ajax.php');?>';

          var form = $('#enquiry').serialize();

                var formdata = new FormData;

                formdata.append('action', 'enquiry');
                formdata.append('enquiry', form);

                $.ajax(endpoint, {
                     type:'POST',
                     data:formdata,
                     processData: false,
                     contentType: false,

                     success: function(res){

                         $('#enquiry').fadeOut(200);

                         $('#successmail').show();

                         $('#enquiry').trigger('reset');

                     },

                     error: function(err){

                         $('#errormail').show();

                     }
                })
        })
      })(jQuery)

</script>
</body>
</html>

Also there’s this part in the functions.php file that actually sends the email

add_action('wp_ajax_enquiry', 'enquiry_form');
add_action('wp_ajax_nopriv_enquiry', 'enquiry_form');
function enquiry_form()
{
     $formdata = [];
     wp_parse_str($_POST['enquiry'], $formdata);

     //Admin email
     $admin_email = get_option('admin_email');

     //Email Headers
     $headers[] = 'Content-Type: text/html; charset=UTF-8';
     $headers[] = 'From: ' . $formdata['fname'] . '  <' . $admin_email . '>';
     $headers[] = 'Reply-to:' . $formdata['email'];

     //Who are we sending the email to?
     $send_to = $admin_email;

     //Subject
     $subject = $formdata['title'];

     //Message
     $message = '<strong>From:</strong>' . $formdata['fname'] . $formdata['lname'] . '<br />' .
                '<strong>Email:</strong>' . $formdata['email'] . '<br />' . '<br />' .
                $formdata['message'];
        ;

        try {
            if(wp_mail($send_to, $subject, $message, $headers) )
            {
                wp_send_json_success('Email sent');
            }
            else {
                wp_send_json_error('Email error');
            }
        } catch (Exception $e)
        {
            wp_send_json_error($e->getMessage());
        }

   wp_send_json_success( $formdata['fname'] );
}
?>

I’d be really glad if someone could help me to find out what is missing here in order to prevent the email from being sent if the fields are not filled properly. I’ve been trying to find the answer on my own for a while and I still don’t have a very clear idea about how I can do that. Thank you very much.

2

Answers


  1. Chosen as BEST ANSWER

    Ok, I managed to make it work, so I'm sharing it in case someone ever needs something similar. I transformed the form classes in variables and then added an if before calling the ajax function, like this:

    <script>
    (function($){
    
       $('#enquiry').submit( function(event){
    
        event.preventDefault();
    
        var fname = $.trim($('.fname').val());
        var lname = $.trim($('.lname').val());
        var email = $.trim($('.email').val());
        var subject = $.trim($('.select').val());
        var message = $.trim($('.message').val());
    
        if (fname === '' || lname === '' || email === '' || subject === '' || message === ''){          
             return false;
            }
    
            else{
    
             var endpoint = '<?php echo admin_url('admin-ajax.php');?>';
    
             var form = $('#enquiry').serialize();
    
             var formdata = new FormData;
    
             formdata.append('action', 'enquiry');
             formdata.append('enquiry', form);
    
             $.ajax(endpoint, {
             type:'POST',
             data:formdata,
             processData: false,
             contentType: false,
    
             success: function(res){
    
               $('#enquiry').fadeOut(200);
    
               $('#successmail').show();
    
               $('#enquiry').trigger('reset');
    
                  },
    
               error: function(err){
    
               $('#errormail').show();
    
                 }
                })
                }
            })
    
          })(jQuery)
    </script>
    

  2. Because you haven’t written any validation code in your ajax callback function.

    To validate your form, you must check each input field’s data before sending an email. Here is an example.

    if(isset($_POST)){ 
    
        if(!isset($_POST['fname']) && $_POST['fname'] == '') {
            wp_send_json_error('Please enter first name')
        }
    
        ...
    
    }
    

    The above code sample is an example of how you should check it before sending an email. wp_send_json_error triggers the error in ajax response so you will be able to display it on the client-side.

    Although data sanitizing is not so much require for email but it is advisable when storing input into the database.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search