jquery select2: error in getting data from php-mysql

后端 未结 2 1927
再見小時候
再見小時候 2020-12-10 09:19

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

相关标签:
2条回答
  • 2020-12-10 09:49

    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.

    0 讨论(0)
  • 2020-12-10 10:05

    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
          };
        }
      }
    });
    
    0 讨论(0)
提交回复
热议问题