jQuery: AJAX contact form for WordPress

jQuery can actually interact very well with WordPress. A typical example of this is surely a contact form enhanced with AJAX. Let's see how things work from the client-side point of view.

The first thing to bear in mind is that a WordPress contact page is self-processed, meaning that the value of the action attribute corresponds to the current page.

For that reason, we need to use this value as our target URL. Then we need to attach an extra POST variable to notify the server-side script (which also handles data validation) that our form has been submitted. We also need to attach another variable to make sure that the output of the server-side script will be displayed only when the form has been actually sent:

(function($) {


 $(function() {
 
  var Contact = function() {
  
   var form = '#contact';
   
   
   
   
   this.process = function() {
   
   
   $(form).submit(function(event) {
   
    var $form = $(this);
    var url = $form.attr('action');
    var data = 'from=' + $('#from', $form).val() + '&email=' + $('#email', $form).val() +
                '&subject=' + $('#subject', $form).val() +
                '&message=' + $('#message', $form).val() +
                '&captcha=' + $('#captcha', $form).val() +
                '&contact-submit=Send&ajax=true';
    
    $.ajax({
     type: 'POST',
     dataType: 'text',
     url: url,
     data: data,
     success: function(txt) {
     
         $('div.success, div.error', $form).remove();
     
      $(txt).prependTo($('ul', $form));
      
      $('html, body').animate({
       scrollTop: $form.offset().top
      }, 500);
      
     
     
     }
     
    });
    
    
    event.preventDefault();
   
   
   });
   
   }
  
  
  };
  
  var contact = new Contact();
  
  if($('#contact').length) {
  
   contact.process();
   
  }
 
 
 });


})(jQuery);

In the success() callback method we remove any message generated by the server-side script before adding further messages. Then we use the scrollTop property to make the entire page scroll up to the top of the form:

$('div.success, div.error', $form).remove();
     
$(txt).prependTo($('ul', $form));
      
$('html, body').animate({
 scrollTop: $form.offset().top
}, 500);

You can see the demo below.

2 thoughts on “jQuery: AJAX contact form for WordPress”

Leave a Reply

Note: Only a member of this blog may post a comment.