WordPress admin-ajax.php 在使用自定义代码调用时返回 500/400 状态。

huangapple go评论88阅读模式
英文:

WordPress admin-ajax.php gives a 500/400 status when called with custom code

问题

我创建了一个小脚本来处理一个下拉选择框,该下拉选择框从自定义的MySQL表中检索数据。该脚本使用了admin-ajax.php,并且在我的本地MAMP上运行得非常完美。然而,当我将文件上传到Bluehost服务器时,如果以管理员身份登录,请求返回500状态。如果我没有登录,则返回400错误请求。而且,即使我没有登录,页面上仍然显示着管理顶部栏,并且其他用户也能看到。我完全不知道发生了什么。

以下是我的代码:

<script>
jQuery(document).ready(function($) {
    // 第一个下拉菜单 (#region_filter) 的变化事件监听器
    $('#region_filter').on('change', function() {
        // 获取选定的地区值
        var selectedRegions = $(this).val();

        // 发送一个用于检索所选地区对应区域的AJAX请求
        $.ajax({
            url: "domain.org/wp-admin/admin-ajax.php",
            type: 'POST',
            data: {
                action: 'eAtlasFiltersRegions',
                regions: selectedRegions
            },
            success: function(response) {
                // 解析JSON响应
                var areas = JSON.parse(response);

                // 清除并更新第三个下拉菜单 (#isra_filter) 选项
                var israDropdown = $('#isra_filter');
                israDropdown.empty();
                israDropdown.append($('<option value="">搜索区域名称</option>'));
                israDropdown.append($('<option value="all">选择全部</option>'));

                // 将检索到的区域名称添加到下拉菜单中
                areas.forEach(function(area) {
                    israDropdown.append($('<option value="' + area + '">' + area + '</option>'));
                });

                // 刷新下拉菜单以应用更改
                israDropdown.dropdown('refresh');
            }
        });

    });

});
</script>

在functions.php中,我编写了以下内容:

add_action('wp_ajax_eAtlasFiltersRegions', 'eAtlasFiltersRegions');

function eAtlasFiltersRegions(){
    global $wpdb;
    
    if (isset($_POST['regions'])) {
        // 从AJAX请求中获取选定的地区
        $selectedRegions = $_POST['regions'];
        console.log($selectedRegions);

        // 构建SQL查询以根据选定的地区检索区域
        $query = "SELECT DISTINCT area_name FROM isra_map_area_names WHERE region_code IN (SELECT region_code FROM isra_map_regions WHERE region IN (";
        $regionValues = array_map(function($region) {
            // 对每个选定的地区进行清理和转义
            return "'" . addslashes($region) . "'";
        }, $selectedRegions);
        $query .= implode(",", $regionValues) . ")) ORDER BY `area_name` ASC";
        // 执行查询
        $query_results = $wpdb->get_results($query);

        // 从查询结果中提取区域名称
        $areaNames = array();
        foreach ($query_results as $result) {
            $areaNames[] = stripslashes($result->area_name);
        }

        // 将区域名称作为JSON响应返回
        echo json_encode($areaNames);
    } else {
        // 如果没有选择地区,则返回空的JSON响应
        if (isset($_POST['regions']) && $_POST['regions'] == '') {
            $query_area_name = $wpdb->get_results("SELECT * FROM isra_map_area_names ORDER BY `area_name` ASC", ARRAY_A);
            // 从查询结果中提取区域名称
            $areaNames = array();
            foreach ($query_results as $result) {
                $areaNames[] = stripslashes($result->area_name);
            }

            // 将区域名称作为JSON响应返回
            echo json_encode($areaNames);
        }
    }
    wp_die();

}

WordPress环境在本地和服务器上是相同的,插件也是相同的。有人遇到过同样的问题吗?我的代码中有什么错误?

英文:

I created a small script to handle a dropdown select that retrieves data from a custom MySQL table. The script uses admin-ajax.php, and it works perfectly on my local MAMP. However when I uploaded the files on Bluehost server I have a 500 status for the request if I am logged in as administrator. If I ma not logged in, I have a 400 bad request. Moreover the page appears with the administration top bar, even if I am not logged in and it appears to other users as well. I have no idea of what happened

Here's my code

&lt;script&gt;
jQuery(document).ready(function($) {
    // Event listener for changes in the first dropdown (#region_filter)
    $(&#39;#region_filter&#39;).on(&#39;change&#39;, function() {
        // Fetch selected region values
        var selectedRegions = $(this).val();

        // Make an AJAX request to retrieve corresponding areas for selected regions
        $.ajax({
            url: &quot;domain.org/wp-admin/admin-ajax.php&quot;,          
            type: &#39;POST&#39;,
            data: {
                action:&#39;eAtlasFiltersRegions&#39;,
                regions: selectedRegions
            },
            success: function(response) {
                // Parse the JSON response
                var areas = JSON.parse(response);

                // Clear and update the third dropdown (#isra_filter) options
                var israDropdown = $(&#39;#isra_filter&#39;);
                israDropdown.empty();
                israDropdown.append($(&#39;&lt;option value=&quot;&quot;&gt;Search area names&lt;/option&gt;&#39;));
                israDropdown.append($(&#39;&lt;option value=&quot;all&quot;&gt;SELECT ALL&lt;/option&gt;&#39;));

                // Add retrieved area names to the dropdown
                areas.forEach(function(area) {
                    israDropdown.append($(&#39;&lt;option value=&quot;&#39; + area + &#39;&quot;&gt;&#39; + area + &#39;&lt;/option&gt;&#39;));
                });

                // Refresh the dropdown to apply changes
                israDropdown.dropdown(&#39;refresh&#39;);
            }
        });

    });
 
});
&lt;/script&gt; 

and on the functions.php I wrote the following:

add_action(&#39;wp_ajax_eAtlasFiltersRegions&#39;, &#39;eAtlasFiltersRegions&#39;);

function eAtlasFiltersRegions(){
    global $wpdb;
    
    if (isset($_POST[&#39;regions&#39;])) {
      // Get the selected regions from the AJAX request
      $selectedRegions = $_POST[&#39;regions&#39;];
      console.log($selectedRegions);

      // Construct the SQL query to retrieve areas based on selected regions
      $query = &quot;SELECT DISTINCT area_name FROM isra_map_area_names WHERE region_code IN (SELECT region_code FROM isra_map_regions WHERE region IN (&quot;;
      $regionValues = array_map(function($region) {
          // Sanitize and escape each selected region
          return &quot;&#39;&quot; . addslashes($region) . &quot;&#39;&quot;;
      }, $selectedRegions);
      $query .= implode(&quot;,&quot;, $regionValues) . &quot;)) ORDER BY `area_name` ASC&quot;;
      // Execute the query
      $query_results = $wpdb-&gt;get_results($query);
  
      // Extract area names from the query results
      $areaNames = array();
      foreach ($query_results as $result) {
          $areaNames[] = stripslashes($result-&gt;area_name);
      }
  
      // Return the area names as a JSON response
      echo json_encode($areaNames);
  } else {
      // Return an empty JSON response if no regions are selected
      if (isset($_POST[&#39;regions&#39;]) &amp; $_POST[&#39;regions&#39;] ==&#39;&#39;) {
        $query_area_name = $wpdb-&gt;get_results(&quot;SELECT * FROM isra_map_area_names ORDER BY `area_name` ASC&quot;, ARRAY_A);
         // Extract area names from the query results
      $areaNames = array();
      foreach ($query_results as $result) {
          $areaNames[] = stripslashes($result-&gt;area_name);
      }
  
      // Return the area names as a JSON response
      echo json_encode($areaNames);
      }
  }
  wp_die();  

}

The wordpress environment is the same on local and on server, as well as the plugins. Has anyone found the same issue? What is the mistake in my code?

答案1

得分: 1

从我所看到的情况来看,你的代码有两个错误:

  1. console.log 在你的PHP文件中,这将引发问题。
  2. 在你的if-else语句的else部分中,当你的结果被分配给$query_area_name时,你正在循环遍历$query_results

试试看,看看是否能解决你的500错误。如果你的500错误消失了,但仍然有问题,可以查看这个资源:

https://stackoverflow.com/questions/48025825/wordpress-admin-ajax-php-400-bad-request?rq=2

英文:

From what I can see, your code as two errors:

  1. console.log is in your PHP file, that will cause issues.
  2. in the else part of your if-else statement, you are looping through $query_results when your results were assigned to $query_area_name.

Give it a try, and see if that fixes your 500 error. If your 500 error goes away and you still have issues, check out this resource:

https://stackoverflow.com/questions/48025825/wordpress-admin-ajax-php-400-bad-request?rq=2

huangapple
  • 本文由 发表于 2023年8月5日 09:08:21
  • 转载请务必保留本文链接:https://go.coder-hub.com/76839769.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定