I asked one question today and it still goes unanswered ( jquery select2: error while getting data from php-mysql ). However, I am trying to fix this and do it, now I am getting a slightly strange problem. I'm not sure why this is happening.
Below is the javascript code.
<div class="form-group"> <label class="col-sm-4 control-label">Product Name</label> <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(term) { return {q: term}; }, results: function(data) { return {results: 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); } 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>
Here is the PHP code ( 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($_GET['q'])); //$search='te'; // 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['tid'], 'text' => $value['tag']); } } else { $data[] = array('id' => '0', 'text' => 'No Products Found'); } // return the result in json echo json_encode($data); ?>
select2 version 3.5
The above code can send / receive a request from the database using fetch.php.
The problem in my database consists of two test and temp entries when I note that either of them creates a new tag.
It should work as follows. if the database matters, then it will not create a new tag with the same name.
Let me know if you need more clarification.
Update:

javascript jquery ajax jquery-select2 select2
Ironic Feb 05 '16 at 19:01 2016-02-05 19:01
source share