WordPress使用SELECT选项将数据发送到AJAX

时间:2021-08-13 作者:Ferhat

I\'m pulling my data from the database and then I want to load the pulled data with ajax but I am not able to do so.

Following is my code.

jQuery code:

jQuery(document).ready(function () {
    jQuery(\'#il\').change(function () {
        let il_id = jQuery(this).val();
        jQuery.ajax({
            type: "POST",
            url: "../wp-content/themes/fancy-lab/ajax.php",
            data: {il: il_id},
            success: function (e) {
                jQuery(\'#ilce\').show();
                jQuery(\'#ilce\').html(e);
            }
        });
    });
});

ajax.php code:

global $wpdb;

$listele=$wpdb->get_results("Select * From wp_ilce where il_id={$_POST[\'il\']}");

foreach ($listele as $val){
    echo "<option value=\'$val->id\'>".$val->ilce."</option>";
}

But I keep getting an error like this get_results returns null. So where is the problem?

<span>Province*</span>
 <select name="il" id="il" class="form-control">
  <option value="" hidden>Select a city.</option>
    <?php global $wpdb;
      $listele = $wpdb->get_results("Select * From wp_il");
         foreach ($listele as $value) {?>

<option value="<?php echo $value->id ?>"><?php echo $value->il ?></option>

           <?php } ?>
</select>
                
 <span>District*</span>
   <select name="ilce" id="ilce" class="form-control" disabled="disabled">
     <option value="" hidden>Please select county</option> </select>
               

Currently there are 4 sciences, I pull them from the database. Thanks to you, I can sort the districts according to those provinces, but no matter which province I choose, my districts always overlap, so after choosing another province, the districts have to be reset and come back. I hope I was able to explain

1 个回复
最合适的回答,由SO网友:Buttered_Toast 整理而成

我将首先检查您的sql查询是什么

print_r("Select * From wp_ilce where il_id={$_POST[\'il\']}");
接下来,将其复制到phpmyadmin 看看它是否返回currect数据,可能是wp_ 前缀不正确,mabe$_POST[\'il\'] 包含不正确的值。

但除此之外,WP还有一种处理ajax请求的方法。

这将有点长,但它将为您提供一个处理ajax请求的起点。

WP有两个用于处理ajax请求的操作,一个是公共的,另一个是用于登录用户的。WP还为所有ajax请求提供了唯一的url。

http://example.com/wp-admin/admin-ajax.php
您的每个ajax请求都应该使用这个url,除非您想使用WP RestAPI,但这是另一个主题。

现在,根据您的JS代码,您可以将其更新到此版本,我冒昧地使用了一些ES6。

($ => {
    $(\'#il\').on(\'change\', e => {
        const ilId = $(e.currentTarget).val();

        $.ajax({
            type: \'POST\',
            url: \'http://your-site/wp-admin/admin-ajax.php\', // wp ajax url
            data: {
                action: \'bt_get_db_il_data\', // the action name we will hook into
                il: ilId
            },
            success: e => {
                // Now on success you can check in the browser console the response
                console.log(e);

                $(\'#ilce\').show();
                $(\'#ilce\').html(e);
            }
        });
    });
})(jQuery);
注意一些变化

  1. url: 现在是处理ajax请求的WP urldata: {} 现在包含action, 这是操作名称,在PHP中,我们将连接并运行代码success: {} 现在也有console.log(e);, 这仅用于调试目的,以查看返回的数据是否符合我们的预期。一切正常后,您可以删除/注释它。好的,JS端很好,现在让我们转到PHP逻辑。

    在里面functions.php 您需要添加以下代码。

    // the $action is the action property that was passed the the data of our ajax request
    // for logged in users, structure: do_action(\'wp_ajax_{$action}\')
    add_action(\'wp_ajax_bt_get_db_il_data\', \'bt_get_db_il_data\');
    
    // for logged out users, structure: do_action(\'wp_ajax_nopriv_{$action}\')
    add_action(\'wp_ajax_nopriv_bt_get_db_il_data\', \'bt_get_db_il_data\');
    
    function bt_get_db_il_data () {
        global $wpdb;
    
        // I assume that $_POST[\'il\'] is supposed to be an integer
        // PHP has a function for retrieving request data
        // for POST requests it like this
        $il = filter_input(INPUT_POST, \'il\', FILTER_SANITIZE_NUMBER_INT);
    
        // now $il will only contain digits, minimising wrong data being passed into your sql query
    
        // in order to prevent SQL injection and other attacks we will use the prepare method
        // the first argumnet is the sql query, notice the %d,
        // this tell the prepare that the value that supposed to be there is a integer
        // the second and on arguments are the values we want to insert into our sql query
        // in our case we only have one, so our first %d (and only in this case), would be replaced with the value of $il
        $listele = $wpdb->get_results($wpdb->prepare("SELECT * FROM {$wpdb->prefix}ilce WHERE ID = %d", $il));
    
        // this is only for testing to see if we get the expected value/s
        //print_r($listele);
    
        // this will store our options html structure
        $options_html = \'\';
    
        foreach ($listele as $val){
            $options_html .= \'<option value="\' . $val->id . \'">\' . $val->ilce . \'</option>\';
        }
    
        echo $options_html; // this line "returns" the data back to our ajax
    
        // this line will stop any other code in our functions.php from runing
        // always add this line
        die;
    }
    
    我添加的注释应该涵盖代码的大部分逻辑,但我会添加一些其他注释。

    在使用sql查询时,始终转义未手动键入的数据,在这种情况下$_POST. 为此,请使用WPprepare.filter_input. 此函数可帮助您验证/清理数据,从而获得预期的数据

  2. 使用print_r, var_dumpvar_export 在构建所需的html结构之前,要确保数据是您所期望的。这还将帮助您了解可以使用哪些可用属性以及如何调用它们
我认为这应该涵盖基本知识,我会为您添加一些其他资源,以帮助您理解和教授其他一些东西。

相关推荐

我的自定义wp-admin php文件停止工作

我在我的;wp管理;两年前的文件夹。两年来,他们工作得很好。现在,它们不显示我的自定义管理面板。相反,我的网站主页出现了。即使我复制了一个原始WordPress php文件并将其重命名为其他文件,它也不会再工作了。早些时候,如果我复制了,例如;轮廓php“;并将其重命名为;测验php“;它仍然有效。现在不是了。如果我重命名文件;关于php“;“到”;大约-1。php“;并粘贴url“;https://example.com/wp-admin/about-1.php";当我登录WordPress时,