drqrdkfue521903877 2016-01-08 05:40
浏览 45
已采纳

Select2 Ajax不匹配结果

My Select2 form is using ajax to load results from the database, but on the front end the the select2 search is returning all results and not the results specific to the search term. After doing some research I realized that the matcher has to be on the server side, but I can't seem to get it working. Here is my code

Code to query the database and return json data

<?php

  $servername = "localhost";
  $username = "myusername";
  $password = "mypassword";

   try {
$conn = new PDO("mysql:host=$servername;dbname=mydatabase", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
   }
    catch(PDOException $e)
   {
   echo "Connection failed: " . $e->getMessage();
   }



  // strip tags may not be the best method for your project to apply extra 
   layer of security but fits needs for this tutorial 
   $search = strip_tags(trim($_GET['q'])); 

 // Do Prepared Query
   $query = $conn->prepare("
   SELECT * FROM (
    SELECT wp_terms.name
   FROM wp_terms
   JOIN wp_term_taxonomy
    ON wp_term_taxonomy.term_id = wp_terms.term_id
    WHERE taxonomy = 'job_listing_region'
    AND count = 0
    ) as T"
     );

    // Add a wildcard search to the search variable
     $query->execute(array(':search'=>"%".$search."%"));


   // Do a quick fetchall on the results
    $list = $query->fetchall(PDO::FETCH_ASSOC);

   // Make sure we have a result
   if(count($list) > 0){
    foreach ($list as $key => $value) {
    $data[] = array('id' => $value['name'], 'text' => $value['name']);              
   } 
    } else {
   $data[] = array('id' => '0', 'text' => 'No Products Found');
   }


// return the result in json
echo json_encode($data);

My jquery

<script>
 jQuery(function($) {
 $(document).ready(function() {
     function matchStart (term, text) {
  if (text.toUpperCase().indexOf(term.toUpperCase()) == 0) {
    return true;
  }

  return false;
}
$( "#regions1" ).select2({        
    ajax: {
        url: "/ajax/connect.php",
        dataType: 'json',
        delay: 250,
        data: function (params) {
            return {
                q: params.term // search term
            };
        },
        processResults: function (data) {
    return {
        results: $.map(data, function(obj) {
            return { id: obj.id, text: obj.text };

            })

        };

        }


},
  minimumInputLength: 3,
  width: "300px",
  placeholder: "Please Select Up To Four Additional Cities"

 });

    });
 });
</script>

and here is an example of my json results

[{"id":"Abanda, AL","text":"Abanda, AL"},{"id":"Abbeville, AL","text":"Abbeville, AL"},{"id":"Adak, AK","text":"Adak, AK"},

Search term not matching results

  • 写回答

1条回答 默认 最新

  • dougu1990 2016-01-08 06:03
    关注

    you have not mentioned the like condition in your sql statement.

    your sql should be something like this

    $query = $conn->prepare("
       SELECT * FROM (
        SELECT wp_terms.name
       FROM wp_terms
       JOIN wp_term_taxonomy
        ON wp_term_taxonomy.term_id = wp_terms.term_id
        WHERE taxonomy = 'job_listing_region'
        AND count = 0 AND search_column LIKE ?    <==== this line
        ) as T"
         );
    
    $query->execute(array("%".$search."%"));
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 软件测试决策法疑问求解答
  • ¥15 win11 23H2删除推荐的项目,支持注册表等
  • ¥15 matlab 用yalmip搭建模型,cplex求解,线性化处理的方法
  • ¥15 qt6.6.3 基于百度云的语音识别 不会改
  • ¥15 关于#目标检测#的问题:大概就是类似后台自动检测某下架商品的库存,在他监测到该商品上架并且可以购买的瞬间点击立即购买下单
  • ¥15 神经网络怎么把隐含层变量融合到损失函数中?
  • ¥15 lingo18勾选global solver求解使用的算法
  • ¥15 全部备份安卓app数据包括密码,可以复制到另一手机上运行
  • ¥20 测距传感器数据手册i2c
  • ¥15 RPA正常跑,cmd输入cookies跑不出来