Ajax and jQuery custom form submission in WordPress

I’m not a tech completely, and I’m trying to build my custom theme for WordPress.
So, I came to a point that I need to implement a custom JS script to send the form data. As far as I understand, it’s going to be a PHP file, but now I’m concentrated on front-end. This is AJAX + jQuery validation.
I don’t want my form to refresh the page after it sends the data, just a simple message telling that everything went successful.

Can anyone have a look at the code I wrote and tell me what’s wrong with it? It took me just two days..

PS – the file, that stores that code is embedded into WP theme properly, with a jQuery as a dependancy. I wonder, do I have to do anything to implement AJAX, or it comes with jQuery?

http://codepen.io/anon/pen/MpdRpE

<form class="form">
  <div class="form__item form__item_no-margin">
    <input type="text" name="firstname" placeholder="What's your name?*" class="firstname" required>
    <p class="error-message">Sorry, but this field can't be empty.</p>
  </div>
  <div class="form__item">
    <input type="text" name="email" placeholder="What's your email address?*" class="email" required>
    <p class="error-message">Oopps, I haven't seen emails like that.</p>
  </div>
  <div class="form__item">
    <textarea name="comment" placeholder="Want to leave any message?*" class="textarea" required></textarea>
    <p class="error-message">Nothing to say at all? Really?</p>
  </div>
  <div class="form__item">
    <input type="button" name="submit" value="Send" class="submit-btn">
    <p class="error-message error-message_main val-error">All the required fields have to be filled out.</p>
    <p class="error-message error-message_main_success val-success">Thanks. I'll contact you ASAP!</p>
  </div>
</form>


.error-message {
 display: none;
}

    jQuery(document).ready(function(){
  jQuery(".submit-btn").click(function(){

    var name = jQuery(".firstname").val();
    var email = jQuery(".email").val();
    var message = jQuery(".textarea").val();

    if(name === "" || email === "" || message === "") {
      jQuery(".val-error", ".error-message").css("display", "block");
    }
    else {
      jQuery.ajax({
        url:"/assets/php/send.php", 
        method:"POST",
        data:{name:firstname, email:email, message:comment},
        success: function(data) {
          jQuery("form").trigger("reset");
          jQuery(".val-success").show(fast);
        }
      });
    }
  });
});

Read more here: Ajax and jQuery custom form submission in WordPress

Leave a Reply

Your email address will not be published. Required fields are marked *