I’m totally lost here. Can anyone check what is going wrong with the form I’m trying to create here? It should send data with Ajax in WP custom theme without storying anything in the DB.

The console gives me an error that “firstname is not defined”, line 67 of jQuery – data:{name:firstname, email:email, message:comment,action:'validate_form'} , but truly, I believe it will be more than that.

<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">This is field is required!</p>
      </div>
      <div class="form__item">
        <input type="text" name="email" placeholder="What's your email address?*" class="email" required>
        <p class="error-message">This is field is required!</p>
      </div>
      <div class="form__item">
        <textarea name="comment" placeholder="Please, leave a message!*" class="textarea" required></textarea>
        <p class="error-message">This is field is required!</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="success-message val-success">Thanks. I'll contact you ASAP!</p>
      </div>
    </form>

And some jQuery:

 jQuery(document).ready(function(){
  jQuery(".submit-btn").click(function(e){
  e.preventDefault();
  var name = jQuery(".firstname").val();
  var email = jQuery(".email").val();
  var message = jQuery(".textarea").val();
  var ajaxUrl = "/wp-admin/admin-ajax.php";

if(name === "" || email === "" || message === "") {
  jQuery(".val-error, .error-message").show();
  jQuery("html, body").animate({
    scrollTop: jQuery(".val-error").offset().top
}, 700)
}
else {
  jQuery.ajax({
    url: ajaxUrl, 
    method:"POST",
    data:{name:firstname, email:email, message:comment,action:'validate_form'},
    success: function(data) {
      jQuery("form").trigger("reset");
      jQuery(".val-success").show(fast);
        }
      });
    }
  });
});

PHP in the functions.php file:

add_action('wp_ajax_myaction', 'my_action_callback');
add_action('wp_ajax_nopriv_myaction', 'my_action_callback');


function my_action_callback(){
 $name= trim($_POST["firstname"]);
 $email = trim($_POST["email"]);
 $comment = trim($_POST["comment"]);

 $page_title = "New form submission";
 $message = "Name: $name nEmail: $email nMessage: $comment";
 mail('some@email.com', $page_title, $message, "Content-type: text/plain; charset="utf-8"n From: some@email.com" );
wp_die();

}

Read more here: WordPress and Ajax form submission


Solution:

If you know the solution of this issue, please leave us a reply in Comment section, to update the question.


Wordpress related questions and answers: