How to use ajax in WordPress Plugin

WordPress provides ajax support to Plugin Developer through wp_ajax_action_name hook.

Here is example to submit contact form using Ajax.admin_footer hook is used to add javascript code to the footer and action name parameter should be send through ajax request and then need to register that hook using add_action(‘wp_ajax_saveContact’,’saveContact’);

 
jQuery(document).ready(function(){
 
  jQuery('#frmContact').submit(function(){
     jQuery.ajax({
       url:"/wp-admin/admin-ajax.php",
       data:jQuery("#frmContact").serialize(),
       type:"POST",
       success:function(response){
         if(response==1){
           alert("Contact saved.");
          }
       }
            
     })
  });
});

Process Form Submission

Here I am registering an a custom hook named wp_ajax_saveContact.If you want to use wp_ajax in frontend then wp_ajax_nopriv_ is used as prefix.$wpdb is used for database operations.Here I am saving records to wp_contacts table.

 
<?php
 add_action('wp_ajax_saveContact','saveContact');
function saveContact(){
global $wpdb;
$table_name = $wpdb->prefix."contacts";
$contact['first_name'] = $_POST['first_name'];
$contact['last_name'] = $_POST['last_name'];
$contact['email']    = $_POST['email'];
$contact['phone'] = $_POST['phone'];
$wpdb->insert($table_name,$contact);
$contact_id = $wpdb->insert_id;
if($contact_id)
echo 1;
exit;
}
?>

Use exit/die

You should always use exit or die at the end of ajax processing code.

Leave a Reply