jQuery select2:从php-mysql获取数据时出错 [英] jquery select2: error in getting data from php-mysql

查看:90
本文介绍了jQuery select2:从php-mysql获取数据时出错的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在本地计算机上测试 select2 插件. 但是出于某种原因.它不是从数据库中收集数据.

I am testing select2 plugin in my local machine. But for some reason. it is not collecting the data from database.

我尝试了多次,但是找不到问题.

I tried multiple times but not able to find the issue.

下面是代码.

<div class="form-group">

   <div class="col-sm-6">
       <input type="hidden" id="tags" style="width: 300px"/>
   </div>
</div> 

<script type="text/javascript">
var lastResults = [];

$("#tags").select2({
    multiple: true,
    placeholder: "Please enter tags",
    tokenSeparators: [","],
    initSelection : function (element, callback) {
        var data = [];
        $(element.val().split(",")).each(function () {
            data.push({id: this, text: this});
        });
        callback(data);
    },
    ajax: {
        multiple: true,
        url: "fetch.php",
        dataType: "json",
        type: "POST",
      data: function (params) {
            return {
                q: params.term // search term
            };
            },
        results: function (data) {
            lastResults = data;
            return data;
        }
    },
    createSearchChoice: function (term) {
        var text = term + (lastResults.some(function(r) { return r.text == term }) ? "" : " (new)");
        return { id: term, text: text };
    },
});

$('#tags').on("change", function(e){
    if (e.added) {
        if (/ \(new\)$/.test(e.added.text)) {
           var response = confirm("Do you want to add the new tag "+e.added.id+"?");
           if (response == true) {
              alert("Will now send new tag to server: " + e.added.id);
              /*
               $.ajax({
                   type: "POST",
                   url: '/someurl&action=addTag',
                   data: {id: e.added.id, action: add},    
                   error: function () {
                      alert("error");
                   }
                });
               */
           } else {
                console.log("Removing the tag");
                var selectedTags = $("#tags").select2("val");
                var index = selectedTags.indexOf(e.added.id);
                selectedTags.splice(index,1);
                if (selectedTags.length == 0) {
                    $("#tags").select2("val","");
                } else {
                    $("#tags").select2("val",selectedTags);
                }
           }
        }
    }
});
</script>

fetch.php

我检查了fetch.php,它工作正常.它正在返回数据.

i checked fetch.php and it is working fine. It is returning the data.

<?php 
    require('db.php');

    $search = strip_tags(trim($_GET['q'])); 
    $query = $mysqli->prepare("SELECT tid,tag FROM tag WHERE tag LIKE :search LIMIT 4");

    $query->execute(array(':search'=>"%".$search."%"));

    $list = $query->fetchall(PDO::FETCH_ASSOC);

    if(count($list) > 0){
       foreach ($list as $key => $value) {
        $data[] = array('id' => $value['tid'], 'text' => $value['tag']);                
       } 
    } else {
       $data[] = array('id' => '0', 'text' => 'No Products Found');
    }

    echo json_encode($data);

    ?>

我正在尝试创建标签,它将检查数据库中的标签. 如果未找到标签,则用户可以创建新标签,该标签将保存在数据库中并显示在用户的用户选择中.

I am trying to create tagging and it will check tag in database. if tag not found then user can create new tag and it will save in database and show in user user selection.

目前,我尚未创建将标签保存在数据库中的页面. 我也尝试使用select2版本3.5和4.0.1 .

At the moment i am not yet created the page to save the tags in database. I tried using select2 version 3.5 and 4.0.1 as well.

这是我第一次尝试使用 select2 插件.因此,请忽略我是否犯了愚蠢的错误.我为此表示歉意.

This is first time is i am trying select2 plugin. So, please ignore if i did silly mistakes. I apologies for that.

感谢您的时间.

我检查了萤火虫,发现数据fetch.php从输入框中没有任何值.它看起来像Ajax中的问题.因为它没有发送q值.

I checked in firebug and found data fetch.php didn't get any value from input box. it looks like issue in Ajax. Because it is not sending q value.

推荐答案

以下是答案.如何从数据库获取数据.

Here is the answer. how to get the data from database.

tag.php

<script type="text/javascript">
var lastResults = [];

$("#tags").select2({
    multiple: true,

    //tags: true,    
    placeholder: "Please enter tags",
    tokenSeparators: [","],
    initSelection : function (element, callback) {
        var data = [];
        $(element.val().split(",")).each(function () {
            data.push({id: this, text: this});
        });
        callback(data);
    },
    ajax: {
        multiple: true,
        url: "fetch.php",
        dataType: "json",
        delay: 250,
        type: "POST",
      data: function(term,page) {
                        return {q: term};
                        //json: JSON.stringify(),
                    },
                    results: function(data,page) {
                        return {results: data};

                    }, 

    },
    minimumInputLength: 2,
      // max tags is 3
    maximumSelectionSize: 3,   
    createSearchChoice: function (term) {
        var text = term + (lastResults.some(function(r) { return r.text == term }) ? "" : " (new)");
       // return { id: term, text: text };
         return {
            id: $.trim(term),
            text: $.trim(term) + ' (new tag)'
        };        
    },
});

$('#tags').on("change", function(e){
    if (e.added) {
        if (/ \(new\)$/.test(e.added.text)) {
           var response = confirm("Do you want to add the new tag "+e.added.id+"?");
           if (response == true) {
              alert("Will now send new tag to server: " + e.added.id);
              /*
               $.ajax({
                   type: "POST",
                   url: '/someurl&action=addTag',
                   data: {id: e.added.id, action: add},    
                   error: function () {
                      alert("error");
                   }
                });
               */
           } else {
                console.log("Removing the tag");
                var selectedTags = $("#tags").select2("val");
                var index = selectedTags.indexOf(e.added.id);
                selectedTags.splice(index,1);
                if (selectedTags.length == 0) {
                    $("#tags").select2("val","");
                } else {
                    $("#tags").select2("val",selectedTags);
                }
           }
        }
    }
});
</script>

fetch.php

<?php 
// connect to database 
require('db.php');

// 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($_POST['term'])); 

// Do Prepared Query 
$query = $mysqli->prepare("SELECT tid,tag FROM tag WHERE tag LIKE :search LIMIT 4");

// 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['tag'], 'text' => $value['tag']);            
   } 
} else {
   $data[] = array('id' => '0', 'text' => 'No Products Found');
}


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

?>

使用上面的代码,我能够从数据库中获取数据.我从SO获得了多个用户的帮助.感谢他们所有人.

With the above code i am able to get the data from database. I get help from multiple users from SO. Thanks to all of them.

但是,我仍在完善其他领域,例如在数据库中添加标签.完成后,我将发布完整的n个最终代码.

However, i am still refining other areas like adding tag in database. Once it completed i will post full n final code.

这篇关于jQuery select2:从php-mysql获取数据时出错的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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