jquery select2: error in getting data from php-mysql

泄露秘密 提交于 2019-11-28 11:45:16

Configuration for select2 v4+ differs from v3.5+

It will work for select2 v4:

HTML

<div class="form-group">
   <div class="col-sm-6">
    <select class="tags-select form-control" multiple="multiple" style="width: 200px;">
    </select>
  </div>
</div>

JS

$(".tags-select").select2({
  tags: true,
  ajax: {
    url: "fetch.php",
    processResults: function (data, page) {
      return {
        results: data
      };
    }
  }
});

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);

?>

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.

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!