Skip to content

AJAX Request Post/Return In WordPress Custom Plugin Development

I am working on a Custom WordPress Plugin development where I need AJAX for hitting and garbing the data without page reload. For this purpose, I read many tutorials and finally ended with the below basic plugin code. To explain in detail, here is the full code…

Plugin File:

<?php
/*
Plugin Name: WP Testing Plugin
Plugin URI: http://www.wordpress.org/WP-Testing-Plugin
Description: A Detailed Description About This Plugin.
Author: Muhammad Hassan
Version: 0.1
Author URI: http://www.wordpress.org
*/

/*____________WP Testing Plugin Admin/Script_____________*/
function wp_testingPlugin_admin() {   

echo "      
    <button id='ClickHere'>Click Here To Hit The Ajax</button>
    <div id='showReturnDataHereOnly'>_________</div>

    <script type='text/javascript'>
        jQuery('#ClickHere').click(function(){
            jQuery.ajax({
                type: 'post',
                data: { 
                    'my_plugin_ajax_submit': 'now',
                    'nonce' : '".wp_create_nonce( 'my_plugin_ajax_submit' )."'
                },
                success: function(response) { 
                    jQuery('#ClickHere').text('Ajax Hitted Successfully');
                    jQuery('#showReturnDataHereOnly').html(response);
                },
                error: function(response) { 
                    jQuery('#ClickHere').text('Error! ');
                    jQuery('#showReturnDataHereOnly').html('<div>Error</div>');
                },
            });
        });
    </script>
";

// Get The Ajax Hit And After Validating, Forward It To Another Function
if (isset($_POST['my_plugin_ajax_submit']))
{
    if ( wp_verify_nonce( $_POST['nonce'], 'my_plugin_ajax_submit' ) )
    {
        my_plugin_ajax_submit();   
    }
}

}

// Desired Function To Be Run After Ajax Hit
function my_plugin_ajax_submit() {        
    echo "<b><u><i>Function Hitted.</i></u></b><br/>";
    echo "<b><u><i>Working Fine.</i></u></b><br/>";
    echo "<b><u><i>Data Returned.</i></u></b><br/>";
    // Below Commented Code Is Working Fine After Clicking Upper Button And Getting An Email.
    //wp_mail( 'user@domain.com', 'my_plugin_ajax_submit() fired', time());
    //return true;
}
/*__________________________________________________________________*/


/*____________WP Testing Plugin Option_____________*/
//Adding "WP Testing Plugin" Menu To WordPress -> Tools
function wp_testingPlugin() {
    //  add_management_page( $page_title, $menu_title, $capability, $menu_slug, $function);                  Menu Under Tools
    add_management_page("WP Testing Plugin By Hassan", "WP Testing Plugin", 'activate_plugins', "WP-Testing-Plugin", "wp_testingPlugin_admin");
}
add_action('admin_menu', 'wp_testingPlugin');
/*__________________________________________________________________*/
?>

This code is working fine partially so I want to know the rest of the bug. It is working fine when I hit the button and it changes the button text but and fills the desired div with whole same plugin web page including my functions data too. Whereas’s I want to fill the desired DIV with the required function data only. What’s the problem here? Need basic steps only to work in this pattern.

Note: In real, I want to build an HTML Form in Plugin page where the user will fill the form and then the form data will be sent to desired function data without reloading the page and will return with that function output.

Advertisement

Answer

I tried my best and got a get around for work but I know that it’s not the best way to get the data because of it is getting full page then we are filtering the required data only. Anyway here is the updated code…

Plugin File:

<?php
/*
Plugin Name: WP Testing Plugin
Plugin URI: http://www.wordpress.org/WP-Testing-Plugin
Description: A Detailed Description About This Plugin.
Author: Muhammad Hassan
Version: 0.1
Author URI: http://www.wordpress.org
*/

/*____________WP Testing Plugin Admin/Script_____________*/
function wp_testingPlugin_admin() {   

echo "      
    <button id='ClickHere'>Click Here To Hit The Ajax</button>
    <div id='showReturnDataHereOnly'>_________</div>

    <script type='text/javascript'>
        jQuery('#ClickHere').click(function(){
            jQuery.ajax({
                type: 'post',
                data: { 
                    'my_plugin_ajax_submit': 'now',
                    'nonce' : '".wp_create_nonce( 'my_plugin_ajax_submit' )."'
                },
                success: function(response) { 
                    jQuery('#ClickHere').text('Ajax Hitted Successfully');                        
// Get The Selected DIV Response Only From This Whole Page
jQuery('#showReturnDataHereOnly').html(jQuery('#my_plugin_ajax_submit_data',response).html());
                },
                error: function(response) { 
                    jQuery('#ClickHere').text('Error! ');
                    jQuery('#showReturnDataHereOnly').html('<div>Error</div>');
                },
            });
        });
    </script>
";

// Get The Ajax Hit And After Validating, Forward It To Another Function
if (isset($_POST['my_plugin_ajax_submit']))
{
    if ( wp_verify_nonce( $_POST['nonce'], 'my_plugin_ajax_submit' ) )
    {
        my_plugin_ajax_submit();   
    }
}

}

// Desired Function To Be Run After Ajax Hit
function my_plugin_ajax_submit() {
    echo "<div id='my_plugin_ajax_submit_data'>";       
      echo "<b><u><i>Function Hitted.</i></u></b><br/>";
      echo "<b><u><i>Working Fine.</i></u></b><br/>";
      echo "<b><u><i>Data Returned.</i></u></b><br/>";
    echo '</div>';
    // Below Commented Code Is Working Fine After Clicking Upper Button And Getting An Email.
    //wp_mail( 'user@domain.com', 'my_plugin_ajax_submit() fired', time());
    //return true;
}
/*__________________________________________________________________*/


/*____________WP Testing Plugin Option_____________*/
//Adding "WP Testing Plugin" Menu To WordPress -> Tools
function wp_testingPlugin() {
    //  add_management_page( $page_title, $menu_title, $capability, $menu_slug, $function);                  Menu Under Tools
    add_management_page("WP Testing Plugin By Hassan", "WP Testing Plugin", 'activate_plugins', "WP-Testing-Plugin", "wp_testingPlugin_admin");
}
add_action('admin_menu', 'wp_testingPlugin');
/*__________________________________________________________________*/
?>

I am still looking for answers so if anyone can help me better then this then will select that answer. I have a suggestion that Can we put our required function in another file so it will be easy for us to get the whole content of that file after getting hit? Also, it will be better if you will help me out for putting JavaScript in another file too.

User contributions licensed under: CC BY-SA
8 People found this is helpful