Jquery select2: duplicate tag recreated

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); /* $.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> 

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.

enter image description here Update:

enter image description here

0
javascript jquery ajax jquery-select2 select2
Feb 05 '16 at 19:01
source share
2 answers

Finally, it works now. I would like to thank @alex and @milz for their support. Here is the complete n final code. Now duplicate tags are not created. However, I am working on adding a tag to the database.

php / html file

 <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, 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', // type: "POST", data: function(term,page) { return { term: term }; }, results: function(data,page) { lastResults = data; return {results: data}; }, }, maximumSelectionSize: 3, minimumInputLength: 3, createSearchChoice: function(term) { console.log($(this).attr('data')); var text = term + (lastResults.some(function(r) { console.log(r.text); console.log(term); 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> 

Here is the php file to get data from the database. 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 //if(isset($_GET)){ $search = strip_tags(trim($_GET['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."%")); $list = $query->fetchall(PDO::FETCH_ASSOC); if(count($list) > 0){ foreach ($list as $key => $value) { $data[] = array('id' => $value['tag'], 'text' => $value['tag']); } } else { $data[] = array('id' => 'No Products Found', 'text' => 'No Products Found'); } echo json_encode($data); ?> 

It took a long time. Almost 3 days. Hope this saves someone.

0
Feb 07 '16 at 18:38
source share

Tags need identifier and text. The problem you are facing is that your text does not match the identifier.

So, even if you write the same text, Select2 considers the new text to be new because the identifier does not match.

To solve your problem, you need to set the identifier with the same value as the text. Change the foreach of your fetch.php to the following:

 foreach ($list as $key => $value) { $data[] = array('id' => $value['tag'], 'text' => $value['tag']); } 

Update: You also need to update the lastResults variable to avoid duplicate tags with the same text. When you bind select2, you need to change the results ajax property to this (based on this answer :

 ajax: { multiple: true, url: "fetch.php", dataType: "json", type: "POST", data: function(term) { return {q: term}; }, results: function(data) { lastResults = data.results; return {results: data}; }, }, 

Pay attention to lastResults = data.results; . Without this, the lastResults variable lastResults always empty and when the createSearchChoice function createSearchChoice executed, it will always return a new tag.

+2
Feb 06 '16 at 18:23
source share



All Articles