WordPress Plugin Development Tutorial Using Ajax

WordPress ajax is very easy to implement and in this tutorial we will learn how to make an ajax form and will develop a plugin regarding that,

Now step by step start

** if you need then visit my plugin development tutorial page to define a plugin and shortcode and learn to create till the fourth step.

First Step: Create a folder inside your plugin folder and give a unique name to that

Second Step: Create a PHP file with the same name ad the created folder

Third Step: define the plugin


Fourth step: define a shortcode and make a form inside the function called by the shortcode and call a javascript function load_my_ajax() on keyup of the field

//adding the shortcode for the login form
add_shortcode("HSWP_FORM", "cm_form");

function cm_form(){
$output_form = hirans_form_perform();
return $output_form;
}

function cm_form_perform(){
?>

Fifth Step: Now create a js folder and create a js file inside the js folder and include an ajax file by using wp_enqueue_script script here my_ajax_url will define the ajax URL object and ajax_url will be used to get the URL for ajax operation here using WordPress admin-ajax.

function add_ajax_file(){
wp_enqueue_script('my-ajax',plugins_url('/js/ajax.js', __FILE__),array('jquery'),true);
// in JavaScript, object properties are accessed as ajax_object.ajax_url, ajax_object.we_value
wp_localize_script( 'my-ajax', 'my_ajax_url',
            array( 'ajax_url' => admin_url( 'admin-ajax.php' )
    ) );
}
add_action('wp_enqueue_scripts','add_ajax_file');

now write the javascript function to handle the ajax operation here my_ajax_function is the function to be called to perform the ajax operation.

function load_my_ajax($){
var id = '1';
jQuery.ajax({
        method: "POST",
        url: my_ajax_url.ajax_url,
        data: { 'action': 'my_ajax_function', 'id': id },
        success: function(response){
        console.log('Success AJAX Call :( /// Return Data: ' + response + ' ) ');
        }
      })
      .done(function( data ) {
        jQuery( '#my_ajax_responce' ).html(data);
      })
      .fail(function( data ) {
        console.log('Failed AJAX Call :( /// Return Data: ' + data);
      });
}

Seventh Step: now create my_ajax_function function and write some code in the plugin PHP file.

function my_ajax_function(){
$id = $_POST['id'];
echo $id;
wp_die();
}
add_action( 'wp_ajax_my_ajax_function', 'my_ajax_function' );
add_action( 'wp_ajax_nopriv_my_ajax_function', 'my_ajax_function' );

Now your plugin is ready to use and you can install the plugin and run the form by using the shortcode [HSWP_FORM]

Thanks for Reading

Share The Post On -

Ads Blocker Image Powered by Code Help Pro

Ads Blocker Detected!!!

We have detected that you are using extensions to block ads. Please support us by disabling these ads blocker.