Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
452 views
in Technique[技术] by (71.8m points)

jquery select2: error in getting data from php-mysql

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.

Below are the code .

<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

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.

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.

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

Thanks for your time.

Edit:

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...