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.
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.
Related
I am building now a Queuing system for my helpdesk system. i have problem in detecting the changes of input value. I want to play the play_sound() function sound when the value of input is incremented. the curent value of input is coming from the rowCount in my SQL Query stored in variable.
screenshot picture link
Input
<input disabled type="text" id="needapproval" id="approval" value="0" class="center" />
My Script
<script type="text/javascript">
function play_sound() {
var audioElement = document.createElement('audio');
audioElement.setAttribute('src', 'Kalimba.mp3');
audioElement.setAttribute('autoplay', 'autoplay');
audioElement.load();
audioElement.play();
}
activateMagic();
function activateMagic() {
setInterval(realTimeData, 1000);
function realTimeData() {
$.ajax({
url: './includes/needapproval.php',
method: 'GET',
dataType: "json",
success: function(res) {
$("#needapproval").val(res.data_count);
},
error: function(err) {
console.log(err);
}
});
}
}
</script>
PHP
require_once "connection.php";
class NeedApprovalStatus extends Connection{
public function needApproval() {
$count_approval = "SELECT * FROM job_request WHERE approval_status LIKE '%Need Approval%' ";
$stmt_count_approval = $this->db->prepare($count_approval);
$stmt_count_approval->execute();
$count = $stmt_count_approval->rowCount();
$data_count = [];
if ($count == 0) {
$data_count = [
'data_count' => 0
];
} else {
$data_count = [
'data_count' => $count
];
}
echo json_encode($data_count);
}
}
$need_approval = new NeedApprovalStatus;
$need_approval->needApproval();
I tried to use onchange event in jquery but it doesn't work. because i think onchange only trigger when you change value on input manually. Any ideas guys?
It would be easier to check the value inside the success function and call play_sound() from there.
function activateMagic() {
var value = 0;
setInterval(realTimeData, 1000);
function realTimeData() {
$.ajax({
url: './includes/needapproval.php',
method: 'GET',
dataType: "json",
success: function(res) {
var newValue = res.data_count;
if(newValue != value) {
play_sound()
$("#needapproval").val(value);
value = newValue;
}
}
...
I'm now working with select2 drop-down plugin. I came situation that I have to add a select2 field which auto populate the existing mail id's in our app. I was able to do so, but I also has to add new mail id's which are not in our app in same field. I do not able work it out. Can any of you please help me out from this...
Here is my view page code.
<input type="hidden" class="select2 to_email w-100" name="to_email[]"
data-role="to_email" data-width="100%" data-placeholder="To" value="">
Js code:
$('body').on('click','[data-button="reply-mail"],[data-click="reply"]', function() {
attach = [];
var $ti = $(this).closest('[data-role="row-list"]').find('[data-role="reply-mail-wrap"]');
var $to_this = $ti.find('[data-role="to_email"]');
var mail_toadr = $ti.find('input[name="to_addr"]').val();
$($to_this).select2({
placeholder: "Search for a contact",
minimumInputLength: 3,
//maximumSelectionLength: 1,
multiple : true,
ajax: {
url: Utils.siteUrl()+'mailbox/get_all_contacts',
type: 'POST',
dataType: 'json',
quietMillis: 250,
data: function (term, page) {
return {
term: term, //search term
page_limit: 100 // page size
};
},
results: function (data, page) {
return { results: data};
}
},
initSelection: function(element, callback) {
return $.getJSON(Utils.siteUrl()+'mailbox/get_all_contacts?email=' + (mail_toadr), null, function(data) {
return callback(data);
});
}
});
});
I know, working example could be better to you, but I'm sorry, I do not know how to do it.
A screen shot for small help:http://awesomescreenshot.com/08264xy485
Kindly help..
I have got a fix for my requirement. If we enter a non-existing value in our field, results: function (data, page) {...} returns an empty array. We can check this as:
results: function (data, page) {
for (var obj in data) {
id = JSON.stringify(data[obj].id);
text = JSON.stringify(data[obj].text);
if (id == '"0"') {
$ti.find('.to_email').select2('val', '<li class="select2-search-choice"><div>'+ text +'</div><a tabindex="-1" class="select2-search-choice-close" onclick="return false;" href="#"></a></li>');
}
}
return { results: data};
}
But, better than this I suggest you to do a check in the area where we fetch result (here: Utils.siteUrl()+'mailbox/get_all_contacts'). I have done this to fix my issue:
function get_all_contacts()
{
// $contacts is the result array from DB.
// $term is the text to search, eg: 111
foreach($contacts as $contact_row) {
$contact_all[] = array('id' => $contact_row['id'], 'text' => $contact_row['primary_email']);
}
if (empty($contact_all)) {
$contact_all = array('0' => array('id' => 'undefinedMAILID_'. $term, 'text' => $term ) );
}
$contact_data['results'] = $contact_all;
send_json_response($contact_all);
}
Getting value in JS:
sel_ids = $('.to_email').select2('val');
console.log(sel_ids);
// console will show - ["value if mail id is existing", "undefinedMAILID_111"]
hope this will help someone.
I'm trying to use DataTable to show all fields of my JSON, but I'm not understand how to use it.
I just need how to populate dataset correctly to read data.
<script>
<?php
var jqxhr = $.ajax({url: api_ricerca_ingredienti, type: "GET",dataType: "json", data: {all: 1, ln : "it",completo:"-1",conteggio: 1}} )
var max=json.items.length;
for (i=0;i<max;i++){
var el=json.items[i];
}
$(".risultato_ricerca").click(function() {
carica_ingrediente($(this).attr('data-id'));
});
})
<?php }?>
var dataSet = [
/*HOW?*/
];
$(document).ready(function() {
$('#example').DataTable( {
data: dataSet,
columns: [
{ title: "Nome" },
{ title: "Stato" },
{ title: "Home" },
{ title: "Utente" },
{ title: "Mi piace" },
{ title: "Contributi" }
]
} );
} );
</script>
<table id="example" class="table table-responsive table-hover table-dynamic filter-head"></table>
First, two comments about your code.
As #Patrick Q stated, your PHP tags are useless: you are writing Javascript, PHP is another things that has nothing to do with your code, so remove <?php and <?php }?>
Then, i can't understand this code:
for (i=0;i<max;i++){
var el=json.items[i];
}
This for is completely useless. you cycle through every element in json.items without performing any operation. At the end you just store the last json.items in the el (without even using el in your code).
By the way, your main question:
As said in the official documentation, your dataSet must contain an array for every row of your table in the format:
var dataSet = [
["john","italy","home","john",15,20],
["john","italy","home","john",15,20]
]
This example will create two identical rows with random data inside.
Assuming every item in your json has name country home user likes contribs fields you will need something like that:
var dataSet = [];
for (i=0;i<json.items.length;i++){
var el = [json.items[i].name,json.items[i].country, json.items[i].home, json.items[i].user, json.items[i].likes, json.items[i].contribs]
dataSet[i] = el;
}
Sorry guys. I've truncated my prev code. Now the building of data array works like a charm. I've just a doubt about a console error:
"jquery.dataTables.min.js:5 Uncaught TypeError: Cannot read property 'aDataSort' of undefined"
I can't show my rows. According with your opinion, what's the problem?
Thank you!
<script>
< ?php
if (isset($_GET) && isset($_GET['id'])){
?>
$( document ).ready(function() {
carica_ingrediente('<?php echo $_GET['id'];?>');
});
<?php }else {?>
$('#query').keypress(function(e) {
if (e.keyCode == $.ui.keyCode.ENTER) {
$('#cerca').click();
}
});
$(document).ready(function() {
var jqxhr = $.ajax({url: api_ricerca_ingredienti, type: "GET",dataType: "json", data: {all: 1, ln : "it",completo:"-1",conteggio: 1}} )
.done(function(json) {
if (json.res==0){
alert( "Inserisci una parola per iniziare la ricerca " );
return;
}
var dataSet = [];
for (i=0;i<json.items.length;i++){
var el = [json.items[i].nome,json.items[i].completo, json.items[i].home, json.items[i].utente, json.items[i].likes, json.items[i].countingredienti];
dataSet[i] = el;
console.log(el);
}
$(".risultato_ricerca").click(function() {
carica_ingrediente($(this).attr('data-id'));
});
$(document).ready(function() {
$('#example').DataTable( {
data: dataSet,
columns: [
{ title: "Nome" },
{ title: "Stato" },
{ title: "Home" },
{ title: "Utente" },
{ title: "Mi piace" },
{ title: "Contributi" }
]
} );
} );
})
.fail(function() {
alert( "error" );
});
});
<?php }?>
</script>
In select2 I have tags loaded by AJAX, if the tag is not found in the db then the user has the option to create a new one. The issue is that the new tag is listed in the select2 box as a term and not as the id (what select to wants - especially becomes a problem when loading the tags again if the user wants to update since only the term and not the id is stored in the db). How can I, on success of adding the term, make it so that select2 recieves the ID and submits the ID instead of the tag name/term?
$(document).ready(function() {
var lastResults = [];
$("#project_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: "framework/helpers/tags.php",
dataType: "json",
data: function(term) {
return {
term: 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
};
},
});
$('#project_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({
url: 'framework/helpers/tags.php',
data: {
action: 'add',
term: e.added.id
},
success: function(data) {
},
error: function() {
alert("error");
}
});
} else {
console.log("Removing the tag");
var selectedTags = $("#project_tags").select2("val");
var index = selectedTags.indexOf(e.added.id);
selectedTags.splice(index, 1);
if (selectedTags.length == 0) {
$("#project_tags").select2("val", "");
} else {
$("#project_tags").select2("val", selectedTags);
}
}
}
}
});
});
Heres part of the switch that does the adding
case 'add':
if (isset($_GET['term'])) {
$new_tag = escape($_GET['term']);
if (Nemesis::insert('tags', 'tag_id, tag_content', "NULL, '{$new_tag}'")) {
// we need to send back the ID for the newly created tag
$search = Nemesis::select('tag_id', 'tags', "tag_content = '{$new_tag}'");
list($tag_id) = $search->fetch_row();
echo $tag_id;
} else {
echo 'Failure';
}
exit();
}
break;
UPDATE: I've done a bit of digging, and what confuses me is that the select2 input does not seem to store the associated ID for the tag/term (see below). I know I could change the attribute with the success callback, but I don't know what to change!
As you have said, you can replace that value, and that is what my solution does. If you search the Element Inspector of Chrome, you will see, bellow the Select2 field, an input with the id project_tags and the height of 1.
The weird thing is that the element inspector of Chrome does not show you the values of the input, as you can see below:
However, you do a console.log($("#project_tags").val()) the input has values (as you see in the image).
So, you can simply replace the text of the new option by the id, inside the success function of the ajax call placed within the $('#project_tags').on("change") function. The ajax call will be something like:
$.ajax({
url: 'framework/helpers/tags.php',
data: {
action: 'add',
term: e.added.id
},
success: function(tag_id) {
var new_val = $("#project_tags")
.val()
.replace(e.added.id, tag_id);
$("#project_tags").val(new_val);
},
error: function() {
alert("error");
}
});
Please be aware that this solution is not bullet proof. For example, if you have a tag with the value 1 selected, and the user inserts the text 1, this will cause problems.
Maybe a better option would be replace everything at the right of the last comma. However, even this might have cause some problems, if you allow the user to create a tag with a comma.
Let me know if you need any more information.
I am using the select2 for on of my search boxes. I'm getting the results from my URL but I'm not able to select an option from it. I want to use the 'product.productName' as the text to be shown after selection. Is there anything that I have missed out or any mistake that I have made. I have included select2.css and select2.min.js,jquery.js
function dataFormatResult(product) {
var markup = "<table class='product-result'><tr>";
markup += "<td class='product-info'><div class='product-title'>" + product.productName + "</div>";
if (product.manufacturer !== undefined) {
markup += "<div class='product-synopsis'>" + product.manufacturer + "</div>";
}
else if (product.productOptions !== undefined) {
markup += "<div class='product-synopsis'>" + product.productOptions + "</div>";
}
markup += "</td></tr></table>";
return markup;
}
function dataFormatSelection(product) {
return product.productName;
}
$(document).ready(function() {
$("#e7").select2({
placeholder: "Search for a product",
minimumInputLength: 2,
ajax: {
url: myURL,
dataType: 'json',
data: function(term,page) {
return {
productname: term
};
},
results: function(data,page) {
return {results: data.result_object};
}
},
formatResult: dataFormatResult,
formatSelection: dataFormatSelection,
dropdownCssClass: "bigdrop",
escapeMarkup: function(m) {
return m;
}
});
});
This is my resut_object
"result_object":[{"productName":"samsung galaxy s3","manufacturer":"Samsung","productOptions":"Color;Memory","productOptiondesc":"Silver;32GB"},{"productName":"samsung salaxy s3","manufacturer":"Samsung","productOptions":"Color;Memory","productOptiondesc":"Graphite;32GB"},{"productName":"samsung galaxy s3","manufacturer":"Samsung","productOptions":"Color;Memory","productOptiondesc":"Silver;16GB"}]
You are missing id attribute for result data. if it has not, it makes option "unselectable".
Example:
$('#e7').select2({
id: function(e) { return e.productName; },
});
Since I was using AJAX, what worked for me was returning something as the ID on processResults:
$(field).select2({
ajax: {
// [..] ajax params here
processResults: function(data) {
return {
results: $.map(data, function(item) {
return {
// proccessResults NEEDS the attribute id here
id: item.code,
// [...] other attributes here
foo: item.bar,
}
})
}
},
},
});
The id param can be a string related to the object property name, and must be in the root of the object. Text inside data object.
var fruits = [{code: 222, fruit: 'grape', color:'purple', price: 2.2},
{code: 234,fruit: 'banana', color:'yellow', price: 1.9} ];
$(yourfield).select2(
{
id: 'code',
data: { results: fruits, text: 'fruit' }
}
);
I have faced the same issue,other solution for this issue is:-
In your response object(In above response Product details object) must have an "id" as key and value for that.
Example:- Your above given response object must be like this
{"id":"1","productName":"samsung galaxy s3","manufacturer":"Samsung","productOptions":"Color;Memory","productOptiondesc":"Silver;32GB"}
SO you don't need this
id: function(object){return object.key;}