简体   繁体   English

jQuery Ajax 请求无法将带有 SQL 查询的所有数据带到字段

[英]jQuery Ajax Request fails to bring all data with SQL Query to fields

i have a form that works by filling the next select fields with data based on the previous ones, it works perfect on Localhost / Xampp with PHP8 but now when i try to get it on my server it only works "once" per category.我有一个表单,它通过使用基于以前的数据填充下一个选择字段来工作,它在使用 PHP8 的 Localhost / Xampp 上工作得很好,但是现在当我尝试将它放在我的服务器上时,它每个类别只能“一次”工作。

My problem simplified.我的问题简化了。

  1. I select category1 and get two results based on that to the next select我选择 category1 并根据下一个选择获得两个结果
  2. Only one of these results works with returning data to the 3rd Select and the other one doesn't return anything with json_encode and only throws an error这些结果中只有一个适用于将数据返回到第 3 个选择,而另一个结果不使用 json_encode 返回任何内容并且只抛出错误

More info: Request that works.更多信息:请求有效。

{
    "request": "2",
    "subcategoryid": "11",
    "alakategoriaID": "15"
}
[

Response which is correct.哪个回答正确。

{
    "ID": "23",
    "name": "Puu 25"
},
{
    "ID": "24",
    "name": "Puu 50"
}

Request that doesn't return anything不返回任何内容的请求

{
        "request": "2",
        "subcategoryid": "10",
        "alakategoriaID": "15"
    }

Main function that contains the select fields etc..包含选择字段等的主要功能。

´´´<script>
  $(function () {

    // Country
    $('#sel_country').change(function () {

      var categoryID = $(this).val();

      // Empty state and city dropdown
      $('#sel_state').find('option').not(':first').remove();
      $('#sel_city').find('option').not(':first').remove();
      $('#varichanger').find('option').not(':first').remove();

      // AJAX request
      $.ajax({
        url: 'helper.php',
        type: 'post',
        data: {
          request: 1,
          categoryID: categoryID
        },
        dataType: 'json',
        success: function (response) {

          var len = response.length;

          for (var i = 0; i < len; i++) {
            var id = response[i]['id'];
            var name = response[i]['name'];

            $("#sel_state").append("<option value='" + id + "'>" + name + "</option>");
          }
        },
        error: function(XMLHttpRequest, textStatus, errorThrown) {
          alert("some error");
        }
      });

      $.ajax({
        url: 'helper.php',
        type: 'post',
        data: {
          request: 3,
          categoryID: categoryID
        },
        dataType: 'json',
        success: function (response) {
          var len = response.length;

          for (var i = 0; i < len; i++) {
            var id = response[i]['id'];
            var name = response[i]['name'];

            $("#varichanger").append("<option value='" + id + "'>" + name + "</option>");
          }
        },
        error: function(XMLHttpRequest, textStatus, errorThrown) {
          alert("some error");
        }
      });

    });

    // State
    $('#sel_state').change(function () {
      var subcategoryid = $(this).val();
      var alakategoriaID = $('#sel_country').val();

      // Empty city dropdown
      $('#sel_city').find('option').not(':first').remove();

      // AJAX request
      $.ajax({
        
        url: 'helper.php',
        type: 'post',
        data: {
          request: 2,
          subcategoryid: subcategoryid,
          alakategoriaID: alakategoriaID
        },
        dataType: 'json',
        success: function (response) {
          console.log(response);

          var len = response.length;

          for (var i = 0; i < len; i++) {
            var id = response[i]['ID'];
            var name = response[i]['name'];

            $("#sel_city").append("<option value='" + id + "'>" + name + "</option>");

          }
        },  
          error: function(XMLHttpRequest, textStatus, errorThrown) {
          alert("some error");
        }
      });
    });
  });
</script>´´´

Helper.php帮手.php

include "pdoconfig.php";
error_reporting(0);

$request = 0;$request = 0;

if(isset($_POST['request'])){
   $request = $_POST['request'];
}

// Fetch subcategory list by categoryID
if(trim($request) == 1){
   $categoryID = $_POST['categoryID'];

   $stmt = $conn->prepare("SELECT * FROM alakategoriat WHERE kategoriaID=:kategoriaID ORDER BY subcategoryname");
   $stmt->bindValue(':kategoriaID', (int)$categoryID, PDO::PARAM_INT);

   $stmt->execute();
   $subcategorysList = $stmt->fetchAll();

   $response = array();
   foreach($subcategorysList as $subcategory){
      $response[] = array(
        "id" => $subcategory['id'],
        "name" => $subcategory['subcategoryname']
      );
   }
   echo json_encode($response);
   exit;
}

// Fetch city list by subcategoryid
if(trim($request) == 2){
   $kategoriaID = $_POST['alakategoriaID'];
   $alakategoriaID = $_POST['subcategoryid'];

  
   $stmt = $conn->prepare("SELECT * FROM tuotteet 
   WHERE kategoriaID=$kategoriaID
   AND alakategoriaID=$alakategoriaID
   ORDER BY productname");

   $stmt->execute();
   $productslist = $stmt->fetchAll();

   $response = array();
   foreach($productslist as $product){
      $response[] = array(
         "ID" => $product['ID'],
         "name" => $product['productname']
      );
   }
   echo json_encode($response);
   exit;
}
if(trim($request) == 3){
   $categoryID = $_POST['categoryID'];

   $stmt = $conn->prepare("SELECT * 
   FROM kategoriavarit 
   INNER JOIN varit ON kategoriavarit.variID = varit.variID
   WHERE kategoriaID=:kategoriaID");
   $stmt->bindValue(':kategoriaID', (int)$categoryID, PDO::PARAM_INT);

   $stmt->execute();
   $varilist = $stmt->fetchAll();

   $response = array();
   foreach($varilist as $vari){
      $response[] = array(
        "id" => $vari['variID'],
        "name" => $vari['varinimi']
      );
   }
   echo json_encode($response);
   exit;
}

you have to save your first category value to session and use it for second time ajax call.您必须将第一个类别值保存到会话并将其用于第二次 ajax 调用。 As per your code you always get trim($request) == 1 because each time ajax call it consider as new request.根据您的代码,您总是会得到trim($request) == 1因为每次 ajax 调用它都将其视为新请求。 So use session or cookie for store and use parent category.所以使用 session 或 cookie 来存储和使用父类别。

Solved the problem by clearing and reinserting my database values and following @Foramkumar Patel's answer通过清除并重新插入我的数据库值并按照@Foramkumar Patel 的回答解决了问题

EDIT: Cancel that, problem was with scandinavian letters in the response from JSON causing many different problems, solved the problem by utf_8 encoding the response.编辑:取消那个,问题是来自 JSON 的响应中的斯堪的纳维亚字母导致了许多不同的问题,通过 utf_8 编码响应解决了这个问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM