How To Use Ajax In WordPress For Data Insertion to database


Follow 5 Simple Steps For Data Insertion Using Ajax

  1. Adding Standard Plugin Information.
  2. Include javascript libraries in plugin.
  3. Creating html form to show in front end.
  4. Adding Event handler using jQuery.
  5.  Adding Ajax functionality in WordPress.

Adding Standard Plugin Information

Remember WordPress will recognize your plugin by this information.

Plugin Name: Demo Plugin
Plugin URI:
Description: My first ajax plugin
Version: 1.0
Author: Prohcj
Author URI:
License: Plugin comes under GPL Licence.

Include Javascript Libraries In Plugin

We are adding our own demo.js file in js folder using wp_enqueue_script.
wp_localize_script script help us to take data from php and make available to Javascript.

//Include Javascript library
wp_enqueue_script('inkthemes', plugins_url( '/js/demo.js' , __FILE__ ) , array( 'jquery' ));
// including ajax script in the plugin Myajax.ajaxurl
wp_localize_script( 'inkthemes', 'MyAjax', array( 'ajaxurl' => admin_url( 'admin-ajax.php')));

Creating Html form To Show In Front end

Wraping HTML form in show_form() function so that we can invoke the function at some specifc time. add_action() will help you to call the show_form() function in the content area using the_content hook.

This step will help you to show your html form in the content area.

function show_form(){
 echo "<form>";
 echo "<label>Name</label>";
 echo "<input type='text' id='dname' name='dname' value=''/><br/>";
 echo "<input type='button' id='submit' name='submit' value='Submit'/>";
 echo "</form>";
add_action('the_content', 'show_form');

Adding Event handler using jQuery

  var name = jQuery("#dname").val();
  type: 'POST',   // Adding Post method
  url: MyAjax.ajaxurl, // Including ajax file
  data: {"action": "post_word_count", "dname":name}, // Sending data dname to post_word_count function.
   success: function(data){ // Show returned data using the function.

Adding Ajax Functionality in WordPress

You need to create ajax call function, here is the code. copy and paste to your functions.php file

  • wp_ajax_function_name –> it allow function calling from admin dashborad only
  • wp_ajax_nopriv_function_name –> it allow function calling from admin as well as all pages 

function post_word_count(){
$name = $_POST['dname'];
global $wpdb;
  'name' => $name

return true;
add_action('wp_ajax_post_word_count', 'post_word_count'); // Call when user logged in
add_action('wp_ajax_nopriv_post_word_count', 'post_word_count'); // Call when user in not logged in

Related Post

Latest Post

Recent Posts Widget

Make sure to never miss a thing...

Get the latest news from the creative industry along with other creative goodies, conveniently delivered to social media.