AJAX Call Via Vanilla JavaScript In WordPress Plugin Development

I ama newbie in WordPress Plugin development in which I have some HTML form on the main plugin page that will get the da

I ama newbie in WordPress Plugin development in which I have some HTML form on the main plugin page that will get the data from the admin who is logged in and a back page where I have some different functions in PHP like to get information from the database etc. To explain in detail, here is the code...

Main Plugin File:

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

/*____________WP Testing Plugin Admin/Script_____________*/
function wp_testingPlugin_admin() {
    echo '
        <form id="searchForm" onsubmit="return searchData(this)">
            <input name="WhatToSearch" type="text" />
            <input type="submit" value="Search"/>
            <input type="reset" value="Reset"/>
            <div id="showReturnData"></div>
        </form>
    ';
    echo '
        <form id="infoForm" onsubmit="return searchInfo(this)">
            <input name="WhatToKnow" type="text" />
            <input type="submit" value="Search"/>
            <input type="reset" value="Reset"/>
            <div id="showReturnInfo"></div>
        </form>
    ';

    echo '
        <script type="text/javascript">
            function searchData(incomingForm) {
                // Confirmation To Add A Data
                var answer = confirm("Are You Sure Want To Search?");
                if (answer){
                    // If User Click Ok Then Execute The Below Code     
                    var FD = new FormData(incomingForm); // Get FORM Element Object
                    FD.append("Function", "DataFunction"); // Adding Extra Data In FORM Element Object To Hit Only This Function In Ajax Call File
                    var ajx = new XMLHttpRequest();
                    ajx.onreadystatechange = function () {
                        if (ajx.readyState == 4 && ajx.status == 200) {
                            document.getElementById("showReturnData").innerHTML = ajx.responseText;             
                        }
                    };
                    ajx.open("POST", "'.plugin_dir_url( __FILE__ ).'my_functions.php", true);
                    ajx.send(FD);
                    document.getElementById("showReturnData").innerHTML = "<div class="error">ERROR: AJAX Did Not Respond.</div>";
                }
                return false; // For Not To Reload Page
            }


            function searchInfo(incomingForm) {
                // Confirmation To Add A Data
                var answer = confirm("Are You Sure Want To Search?");
                if (answer){
                    // If User Click Ok Then Execute The Below Code     
                    var FD = new FormData(incomingForm); // Get FORM Element Object
                    FD.append("Function", "InfoFunction"); // Adding Extra Data In FORM Element Object To Hit Only This Function In Ajax Call File
                    var ajx = new XMLHttpRequest();
                    ajx.onreadystatechange = function () {
                        if (ajx.readyState == 4 && ajx.status == 200) {
                            document.getElementById("showReturnData").innerHTML = ajx.responseText;             
                        }
                    };
                    ajx.open("POST", "'.plugin_dir_url( __FILE__ ).'my_functions.php", true);
                    ajx.send(FD);
                    document.getElementById("showReturnInfo").innerHTML = "<div class="error">ERROR: AJAX Did Not Respond.</div>";
                }
                return false; // For Not To Reload Page
            }

        </script>
    ';
//if you want only logged in users to access this function use this hook
add_action('wp_ajax_searchData', 'searchData');
add_action('wp_ajax_searchInfo', 'searchInfo');
//if you want none logged in users to access this function use this hook
add_action('wp_ajax_nopriv_searchData', 'searchData');
add_action('wp_ajax_nopriv_searchInfo', 'searchInfo');


}
/*__________________________________________________________________*/


/*____________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');
/*__________________________________________________________________*/
?>

And this is my_functions.php file.

<?php
/****************************************************************************/
//Garb The Function Parameter
/****************************************************************************/
$Function = $_POST['Function'];


/****************************************************************************/
// Run Search Function
/****************************************************************************/
if ($Function == "DataFunction"){

    if(!isset($_POST['WhatToSearch'])){
        $WhatToSearch = "Nothing";
    } else {
        $WhatToSearch = $_POST['WhatToSearch'];
    }

    echo "<div class='success'>SUCCESS: Function Is Working Perfectly And Getting Data ".$WhatToSearch.".</div>";
}

/****************************************************************************/
// Run Another Function
/****************************************************************************/
if ($Function == "InfoFunction"){

    if(!isset($_POST['WhatToKnow'])){
        $WhatToKnow = "Nothing";
    } else {
        $WhatToKnow = $_POST['WhatToKnow'];
    }

    echo "<div class='success'>SUCCESS: Function Is Working Perfectly And Getting Data ".$WhatToKnow.".</div>";
}

?>

But my code is not working and not hitting my_functions.php file even. Whats the problem here? Need basic step only to work in this patteren. Currently, I am not sure I am even implementing this correctly as I never used WP AJAX before. So right now, my objective is just to get a basic example working. I appreciate any suggestions on how to accomplish this.

Thank you!

I ama newbie in WordPress Plugin development in which I have some HTML form on the main plugin page that will get the data from the admin who is logged in and a back page where I have some different functions in PHP like to get information from the database etc. To explain in detail, here is the code...

Main Plugin File:

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

/*____________WP Testing Plugin Admin/Script_____________*/
function wp_testingPlugin_admin() {
    echo '
        <form id="searchForm" onsubmit="return searchData(this)">
            <input name="WhatToSearch" type="text" />
            <input type="submit" value="Search"/>
            <input type="reset" value="Reset"/>
            <div id="showReturnData"></div>
        </form>
    ';
    echo '
        <form id="infoForm" onsubmit="return searchInfo(this)">
            <input name="WhatToKnow" type="text" />
            <input type="submit" value="Search"/>
            <input type="reset" value="Reset"/>
            <div id="showReturnInfo"></div>
        </form>
    ';

    echo '
        <script type="text/javascript">
            function searchData(incomingForm) {
                // Confirmation To Add A Data
                var answer = confirm("Are You Sure Want To Search?");
                if (answer){
                    // If User Click Ok Then Execute The Below Code     
                    var FD = new FormData(incomingForm); // Get FORM Element Object
                    FD.append("Function", "DataFunction"); // Adding Extra Data In FORM Element Object To Hit Only This Function In Ajax Call File
                    var ajx = new XMLHttpRequest();
                    ajx.onreadystatechange = function () {
                        if (ajx.readyState == 4 && ajx.status == 200) {
                            document.getElementById("showReturnData").innerHTML = ajx.responseText;             
                        }
                    };
                    ajx.open("POST", "'.plugin_dir_url( __FILE__ ).'my_functions.php", true);
                    ajx.send(FD);
                    document.getElementById("showReturnData").innerHTML = "<div class="error">ERROR: AJAX Did Not Respond.</div>";
                }
                return false; // For Not To Reload Page
            }


            function searchInfo(incomingForm) {
                // Confirmation To Add A Data
                var answer = confirm("Are You Sure Want To Search?");
                if (answer){
                    // If User Click Ok Then Execute The Below Code     
                    var FD = new FormData(incomingForm); // Get FORM Element Object
                    FD.append("Function", "InfoFunction"); // Adding Extra Data In FORM Element Object To Hit Only This Function In Ajax Call File
                    var ajx = new XMLHttpRequest();
                    ajx.onreadystatechange = function () {
                        if (ajx.readyState == 4 && ajx.status == 200) {
                            document.getElementById("showReturnData").innerHTML = ajx.responseText;             
                        }
                    };
                    ajx.open("POST", "'.plugin_dir_url( __FILE__ ).'my_functions.php", true);
                    ajx.send(FD);
                    document.getElementById("showReturnInfo").innerHTML = "<div class="error">ERROR: AJAX Did Not Respond.</div>";
                }
                return false; // For Not To Reload Page
            }

        </script>
    ';
//if you want only logged in users to access this function use this hook
add_action('wp_ajax_searchData', 'searchData');
add_action('wp_ajax_searchInfo', 'searchInfo');
//if you want none logged in users to access this function use this hook
add_action('wp_ajax_nopriv_searchData', 'searchData');
add_action('wp_ajax_nopriv_searchInfo', 'searchInfo');


}
/*__________________________________________________________________*/


/*____________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');
/*__________________________________________________________________*/
?>

And this is my_functions.php file.

<?php
/****************************************************************************/
//Garb The Function Parameter
/****************************************************************************/
$Function = $_POST['Function'];


/****************************************************************************/
// Run Search Function
/****************************************************************************/
if ($Function == "DataFunction"){

    if(!isset($_POST['WhatToSearch'])){
        $WhatToSearch = "Nothing";
    } else {
        $WhatToSearch = $_POST['WhatToSearch'];
    }

    echo "<div class='success'>SUCCESS: Function Is Working Perfectly And Getting Data ".$WhatToSearch.".</div>";
}

/****************************************************************************/
// Run Another Function
/****************************************************************************/
if ($Function == "InfoFunction"){

    if(!isset($_POST['WhatToKnow'])){
        $WhatToKnow = "Nothing";
    } else {
        $WhatToKnow = $_POST['WhatToKnow'];
    }

    echo "<div class='success'>SUCCESS: Function Is Working Perfectly And Getting Data ".$WhatToKnow.".</div>";
}

?>

But my code is not working and not hitting my_functions.php file even. Whats the problem here? Need basic step only to work in this patteren. Currently, I am not sure I am even implementing this correctly as I never used WP AJAX before. So right now, my objective is just to get a basic example working. I appreciate any suggestions on how to accomplish this.

Thank you!

Share Improve this question asked Feb 29, 2020 at 15:42 Muhammad HassanMuhammad Hassan 5514 gold badges8 silver badges23 bronze badges
Add a comment  | 

2 Answers 2

Reset to default 1

Thanks Muhammad, Your solution is a fantastic working framework on which to base real world AJAX calls. I just added this code to the plugin main php file for a shortcode so I could use it in the Front End too.

//For front end use in production
add_shortcode('wp_testingPlugin_shortcode', 'wp_testingPlugin_shortcode');
function wp_testingPlugin_shortcode() {
    wp_enqueue_script( 'ajax-script', plugin_dir_url( __FILE__ ).'my_javascript.js',  array('jquery') );
    wp_localize_script( 'ajax-script', 'my_ajax_object', array( 'ajax_url' => admin_url( 'admin-ajax.php' ) ) );
    return '<form id="searchForm">
        <input name="WhatToSearch" type="text" />
        <input type="submit" value="Search"/>
        <input type="reset" value="Reset"/>
        <div id="showReturnData"></div>
    </form>';
}

Finally after trying my best, here I am sharing the working complete basic example of my question in easy steps. This answer is also considered as a full Ajax Plugin Example in a professional way. I now recommend keeping every file separate for better, clean and comfortable coding...

Main Plugin File:

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

// Calling All PHP File To Load
include('my_functions.php');

/*____________WP Testing Plugin Admin/Script_____________*/
function wp_testingPlugin_admin() {
    echo '
        <form id="searchForm">
            <input name="WhatToSearch" type="text" />
            <input type="submit" value="Search"/>
            <input type="reset" value="Reset"/>
            <div id="showReturnData"></div>
        </form>
    ';
}
/*__________________________________________________________________*/

/*____________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');
/*__________________________________________________________________*/
?>

my_functions.php

<?php
add_action( 'admin_enqueue_scripts', 'my_enqueue' );
function my_enqueue() {
      wp_enqueue_script( 'ajax-script', plugin_dir_url( __FILE__ ).'my_javascript.js', array('jquery') );
      wp_localize_script( 'ajax-script', 'my_ajax_object', array( 'ajax_url' => admin_url( 'admin-ajax.php' ) ) );
}
/****************************************************************************/
// Run Search Function
/****************************************************************************/
/* Register This Function When This File Is Loaded To Call By WordPress AJAX */
add_action('wp_ajax_nopriv_SearchFunction', 'ajaxSearchFunction'); // For Web Visitors
add_action('wp_ajax_SearchFunction', 'ajaxSearchFunction'); // For Admin User
function ajaxSearchFunction(){
    if($_POST['WhatToSearch'] == ""){
        $WhatToSearch = "Nothing";
    } else {
        $WhatToSearch = $_POST['WhatToSearch'];
    }
    echo "<div class='success'>SUCCESS: Function Is Working Perfectly And Getting Data ".$WhatToSearch.".</div>";
}
?>

my_javascript.js

jQuery(document).ready(function() {
jQuery('#searchForm').on("submit",function(e) {
var incomingData = jQuery('#searchForm').serializeArray();
incomingData.push({name: 'action', value: 'SearchFunction'});
alert(JSON.stringify(incomingData));
jQuery.ajax({
type: 'post',
url: my_ajax_object.ajax_url,
data: incomingData,
success: function(response) {
jQuery('#showReturnData').html(response);
},
error: function(response) {
jQuery('#showReturnData').html('<div">Error</div>');
},
});
return false; // For Not To Reload Page
});
});

Thanks for reading this.

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744634857a4585084.html

相关推荐

  • AJAX Call Via Vanilla JavaScript In WordPress Plugin Development

    I ama newbie in WordPress Plugin development in which I have some HTML form on the main plugin page that will get the da

    2天前
    10

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信