WordPress自定义插件开发中的纯JavaScript基本AJAX调用 [英] Pure JavaScript Basic AJAX Call In WordPress Custom Plugin Development

查看:76
本文介绍了WordPress自定义插件开发中的纯JavaScript基本AJAX调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一个自定义WordPress插件,该插件在主插件页面上有一些HTML表单,在后页中有一些PHP的功能,例如从数据库中获取信息等.下面详细说明代码...

I am developing a Custom WordPress Plugin in which I have some HTML form on the main plugin page and a back page where I have some functions in PHP like to get information from the database etc. To explain in detail, here is the code...

主插件文件:

<?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 '
        <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 '
        <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", "SearchFunction"); // 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
            }
        </script>
    ';
//if you want only logged in users to access this function use this hook
add_action('wp_ajax_ACTION_NAME', 'searchData');

//if you want none logged in users to access this function use this hook
add_action('wp_ajax_nopriv_ACTION_NAME', 'searchData');

}
/*__________________________________________________________________*/


/*____________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
/****************************************************************************/
//Garb The Function Parameter
/****************************************************************************/
$Function = $_POST['Function'];


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

    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 == "AnotherFunction"){
    echo "<div class='success'>SUCCESS: Another Function Is Working Perfectly.</div>";
}

?>

但是我的代码不起作用,甚至没有命中my_functions.php文件.这里有什么问题?仅需要基本步骤即可在此模式下工作.

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.

推荐答案

最后在得到 thaikolja 的帮助后,在这里,我将通过简单的步骤分享问题的完整示例.此答案也被视为完整的基本Ajax插件示例.现在,我个人建议将每个文件分开存放,以实现更好,干净和舒适的编码.

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

主插件文件:

<?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
*/

// 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. If you like this basic example then Vote up the question and answer to help others too.

这篇关于WordPress自定义插件开发中的纯JavaScript基本AJAX调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆