jQuery autocomplete retrieve data from database - javascript

I have implemented jQuery autocomplete function for my web, which is working fine. But I want the result of the autocomplete to retrieve only the data of a particular person and not the complete database result.
Below is the jQuery for the autocomplete
jQuery(document).ready(function($){
$('.product_desc').autocomplete({source:'functions/products.php?', minLength:2});
products.php
//Path for the databsae
<?php
include '../include/configuration.php';
if ( !isset($_REQUEST['term']) )
exit;
$rs = mysql_query('select id,item_name,fk_vendor_id from item where item_name like "%'. mysql_real_escape_string($_REQUEST['term']).'%" order by item_name asc ', $con);
$data = array();
if ( $rs && mysql_num_rows($rs) )
{
while( $row = mysql_fetch_array($rs, MYSQL_ASSOC) )
{
$data[] = array(
'label' => $row['item_name'],
'value' => $row['item_name']
);
}
}
else
{
$data[] = array(
'label' => 'not found',
'value' =>''
);
}
// jQuery wants JSON data
echo json_encode($data);
flush();
?>
Any solution will be appreciated.

Try this:
$(".product_desc").autocomplete({
source: "functions/products.php",
minLength: 2,
select: function(event,ui){
//do something
}
});

Try this code, Any text field having class .search the auto complete suggestion will works on server side in ajax.php file you need to return array as below:
$response = ['Computer', 'Mouse', 'Keyboard', 'Monitor'];
echo json_encode($response);
Here is sample code for auto suggest.
$(document).on('keyups','.search',function() {
$(this).autocomplete({
source: function( request, response ) {
if (request.term != "") {
$.ajax({
url: "ajax.php",
dataType: "json",
method: "post",
data: {
name: request.term
},
success: function (data) {
if (data != "") {
response($.map(data, function (item) {
var name = item.name;
return {
label: name,
value: name,
data: item
}
}));
}
}
});
}
},
autoFocus: true,
minLength: 2,
select: function( event, ui ) {
var name = ui.item.data;
$(this).val(name);
}
});
});

Related

JQuery Ajax goes in error

My ajax function goes in error after I set the dataType to Json.
That's the code:
Ajax script:
$('#da').on("change",function() {
$.ajax({
url: "callAjaxIndex.php",
type: "POST",
dataType: "json",
data: {
method: 1,
id: $('#da').val(),
},
success: function() {
alert('test');
},
error: function() {
alert('error');
}
});
});
callAjaxIndex.php
<?PHP
require('includes/core.php');
if ( isset($_POST['method']) ) {
$sql = "SELECT tratte.nome as 'nome_arrivo', tratte.id as 'id_arrivo' FROM tariffe, tratte WHERE id_arrivo = tratte.id AND id_partenza = '".$_POST['id']."'";
$query = $conn->query($sql);
while ( $tariffe = $query->fetch_array() ) {
$result[] = array(
'id' => $tariffe['id_arrivo'],
'nome' => $tariffe['nome_arrivo']
);
}
echo json_encode($result);
}
?>
What's wrong?
Thank you
You can try this
$(document).on('change', '#da', function(){
$.post("callAjaxIndex.php", {'method': 1, 'id': $(this).val()}, function(data){
var d = $.parseJSON(data); //here is the data parsed as JSON
//data is that returned from callAjaxIndex.php file
});
});
<?php
require('includes/core.php');
if ( isset($_POST['method']) ) {
$sql = "SELECT tratte.nome as nome_arrivo, tratte.id as id_arrivo FROM tariffe INNER JOIN tratte ON id_arrivo = tratte.id WHERE id_partenza = '".$_POST['id']."'";
$query = $conn->query($sql);
while ( $tariffe = $query->fetch_array() ) {
$result[] = array(
'id' => $tariffe['id_arrivo'],
'nome' => $tariffe['nome_arrivo']
);
}
echo json_encode($result);
}
You can find out the error by changing your function to this:
//other code
error: function(data)
{
console.log(data.responseText)
}
//other code
This will tell you why it fails, might be something generic but better than 'error'
Also note:
this was done from a phone so excuse any mistakes
I'd rather this be treated as a comment until I can get to a machine to help more :)

jQuery select2: duplicate tag getting recreated

I asked a question earlier today (jquery select2: error in getting data from php-mysql). However, I am trying to fix it and doing that now I am getting bit strange issue. I am not sure why it is happening like this.
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 is 3.5
Above code is able to send/receive request from database by using fetch.php.
Problem is in my database there are two records test & temp when I tag any one of them it create new tag.
It should work like this: if database have value then it won't create the new tag with same name.
Update
Tags need an id and a text. The issue you're facing is that your text doesn't match the id.
So, even if you write the same text, Select2 thinks the new text is a new option because the id don't match.
To solve your issue, you need to set the id 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 variable lastResults to avoid the duplication of tags with the same text. When you bind select2, you need to change the results property of ajax 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};
},
},
Note the lastResults = data.results;. Without this, the lastResults variable is always empty and, when the createSearchChoice function is executed, it will always return a new tag.
Finally it is working now. I would like to thanks #alex & #milz for their support.
Here is the full n final code. Now duplicate tags are not creating. However, i am working to add tag in 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 the data from 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 lots of time. Almost 3 days. I hope it will save someone efforts.
Apply the changes as in the select2.min.js (v4.0.6-rc.1) code snippet below
section 1
c.on("results:select", function() {
var a = e.getHighlightedResults();
if (0 !== a.length) {
var c = b.GetData(a[0], "data");
"true" == a.attr("aria-selected") ? e.trigger("close", {}) : e.trigger("select", {
//custom select2 tagging
if(a.attr("aria-selected")){
c.id = c.id + 1;
}
e.trigger("select", {
data: c
})
//"true" == a.attr("aria-selected") ? e.trigger("close", {}) : e.trigger("select", {
// e.trigger("select", {
// data: c
// })
}
})
section 2
this.on("query", function(b) {
a.isOpen() || a.trigger("open", {}), this.dataAdapter.query(b, function(c) {
//custom select2 tagging
let searchInput = $(".select2-search__field").val();
searchInput = {results: [{id: searchInput, text: searchInput}]};
a.trigger("results:all", {
data: c,
data: searchInput,
query: b
})
})
})

Hide value in Bootstrap Typeahead

I'm using Bootstrap Typeahead with PHP to display a list from a database using source.php:
<?php
if (isset($_POST['query'])) {
require( "config.php" );
$conn = new PDO( DB_DSN, DB_USERNAME, DB_PASSWORD );
$query = $_POST['query'];
$sql = "SELECT * FROM articles WHERE title LIKE '%{$query}%'";
$array = array();
foreach ($conn->query($sql) as $row) {
$array[] = $row['title'] . ',' . $row['id'];
}
// Return the json array
echo json_encode($array);
}
?>
You can see that I add both 'title' and 'id' to the array. All I want it to display in the typeahead is the title but I need the id for the links. Here is the JS:
$('#typeahead').typeahead({
source: function (query, process) {
$.ajax({
url: "source.php",
type: "POST",
data: 'query=' + query,
dataType: 'JSON',
async: true,
success: function(data){
process(data);
}
})
},
sorter: function (items) {
items.unshift(this.query); // Includes a new row with exact search query
return items.sort();
},
updater: function (item) {
document.location = "/companies/" + item.replace(/ /g, '-').replace(/\,/g,'/').toLowerCase() + "/";
return item;
}
});
In the line beginning document.location I replace the comma between the two values with a forward slash and it works e.g. /england/123/. But it's the typeahead display that shows it as England,123 rather than just England.
Any help would be greatly appreciated.
OK managed to get a result with the following:
PHP:
if (isset($_POST['query'])) {
require( "config.php" );
$conn = new PDO( DB_DSN, DB_USERNAME, DB_PASSWORD );
$query = $_POST['query'];
$sql = "SELECT * FROM articles WHERE title LIKE '%{$query}%'";
$array = array();
foreach ($conn->query($sql) as $row) {
$array[] = array('label' => $row['title'], 'id' =>$row['id']);
}
// Return the json array
echo json_encode($array);
}
JS:
$('#typeahead').typeahead({
source: function (query, process) {
$.ajax({
url: "http://www.stubowker.com/amex/cms/source.php",
type: "POST",
data: 'query=' + query,
dataType: 'JSON',
async: true,
success: function(data){
objects = [];
map = {};
$.each(data, function(i, object) {
map[object.label] = object;
objects.push(object.label);
});
process(objects);
}
})
},
sorter: function (items) {
items.unshift(this.query); // Includes a new row with exact search query
return items.sort();
},
updater: function (item) {
document.location = "/companies/" + map[item].label.replace(/ /g, '-').toLowerCase() + "/" + map[item].id +
"/";
return item;
}
});

Ajax with map, getting data

I'm trying to use the $.map in ajax and I don't success with getting the data from json array. I'll show you the json file, the ajax code and the json output i get. Hope you can help me, thank you very much :) and sorry for my english! Here is the ajax:
$.ajax({
url: 'searchapi.php',
dataType: "jsonp",
data: {
featureClass: "P",
style: "full",
maxRows: 12,
name_startsWith: request.term
},
success: function( data ) {
response( $.map(data.table, function( item ) { //dont get this line!
return {
label: item.trid,
value: item.trid
}
}));
}
});
And here is the json file:
<?php
$host = "localhost";
$user = "root";
$pass = "";
$databaseName = "mydb";
$con = mysql_connect($host,$user,$pass);
$dbs = mysql_select_db($databaseName, $con);
$data = ("select * from table;");
$json = array();
$result = mysql_query($data);
while($row = mysql_fetch_array ($result))
{
$array = array(
'trid' => $row['name'],
);
array_push($json, $array);
}
$jsonstring = json_encode($json);
echo $jsonstring;
die();
?>
Here is the json output:
[{"name":"Emma"},{"name":"Eric"},{"name":"Peter"},{"name":"Sam"},{"name":"Roger"},{"name":"Sven"},{"name":"Julia"}]
You are referring to the wrong key, try it like this
$.map(data, function( item ) { //dont get this line!
return {
label: item.name,
value: item.name
}
})

Trying to get tag-it to work with an AJAX call

Trying to get tag-it to work with an ajax call.
Everything works so far. Except, I am unable to assign a tagSource via an ajax call.
In firebug, the 'data' is returning:
["Ruby","Ruby On Rails"]
But its not showing up as I type into the input box.
$('.tags ul').tagit({
itemName: 'question',
fieldName: 'tags',
removeConfirmation: true,
availableTags: ["c++", "java", "php", "javascript", "ruby", "python", "c"],
allowSpaces: true,
// tagSource: ['foo', 'bar']
tagSource: function() {
$.ajax({
url: "/autocomplete_tags.json",
dataType: "json",
data: { term: 'ruby' },
success: function(data) {
console.log(data);
return data;
}
});
}
});
console.log(data) returns ["Ruby", "Ruby On Rails"].
Am I missing something here? Anyone else got this to work?
Seems this question hasn't been answered for a long time, I bet you have already found a solution but for those who haven't here is my answer:
The indention got all messed up when i copied from my code ;)
<input type="hidden" name="tags" id="mySingleField" value="Apple, Orange" disabled="true">
Tags:<br>
<ul id="mytags"></ul>
<script type="text/javascript">
jQuery(document).ready(function() {
jQuery("#mytags").tagit({
singleField: true,
singleFieldNode: $('#mySingleField'),
allowSpaces: true,
minLength: 2,
removeConfirmation: true,
tagSource: function( request, response ) {
//console.log("1");
$.ajax({
url: "search.php",
data: { term:request.term },
dataType: "json",
success: function( data ) {
response( $.map( data, function( item ) {
return {
label: item.label+" ("+ item.id +")",
value: item.value
}
}));
}
});
}});
});
and the "search.php" you can find this in some autocomplete jQuery examples actually.
<?php
$q = strtolower($_GET["term"]);
if (!$q) return;
$items = array(
"Great Bittern"=>"Botaurus stellaris",
"Little Grebe"=>"Tachybaptus ruficollis",
"Black-necked Grebe"=>"Podiceps nigricollis",
"Little Bittern"=>"Ixobrychus minutus",
"Black-crowned Night Heron"=>"Nycticorax nycticorax",
"Heuglin's Gull"=>"Larus heuglini"
);
function array_to_json( $array ){
if( !is_array( $array ) ){
return false;
}
$associative = count( array_diff( array_keys($array), array_keys( array_keys( $array )) ));
if( $associative ){
$construct = array();
foreach( $array as $key => $value ){
// We first copy each key/value pair into a staging array,
// formatting each key and value properly as we go.
// Format the key:
if( is_numeric($key) ){
$key = "key_$key";
}
$key = "\"".addslashes($key)."\"";
// Format the value:
if( is_array( $value )){
$value = array_to_json( $value );
} else if( !is_numeric( $value ) || is_string( $value ) ){
$value = "\"".addslashes($value)."\"";
}
// Add to staging array:
$construct[] = "$key: $value";
}
// Then we collapse the staging array into the JSON form:
$result = "{ " . implode( ", ", $construct ) . " }";
} else { // If the array is a vector (not associative):
$construct = array();
foreach( $array as $value ){
// Format the value:
if( is_array( $value )){
$value = array_to_json( $value );
} else if( !is_numeric( $value ) || is_string( $value ) ){
$value = "'".addslashes($value)."'";
}
// Add to staging array:
$construct[] = $value;
}
// Then we collapse the staging array into the JSON form:
$result = "[ " . implode( ", ", $construct ) . " ]";
}
return $result;
}
$result = array();
foreach ($items as $key=>$value) {
if (strpos(strtolower($key), $q) !== false) {
array_push($result, array("id"=>$value, "label"=>$key, "value" => strip_tags($key)));
}
if (count($result) > 11)
break;
}
echo array_to_json($result);
?>
check this out:
How to get tagSource to work with $.ajax()? (from tag-it's github issue list).
this is an example:
HTML file:
<!doctype html>
<html lang="en">
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.2/jquery.min.js" type="text/javascript" charset="utf-8"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.12/jquery-ui.min.js" type="text/javascript" charset="utf-8"></script>
<script src="js/tag-it.js" type="text/javascript" charset="utf-8"></script>
<link rel="stylesheet" type="text/css" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1/themes/flick/jquery-ui.css">
<link href="css/jquery.tagit.css" rel="stylesheet" type="text/css">
<script type="text/javascript">
$(document).ready(function() {
$("#mytags").tagit({
tagSource: function(search, showChoices) {
$.ajax({
url: "auto.php",
data: {search: search.term},
success: function(choices) {
showChoices(choices);
}
});
}
});
});
</script>
</head>
<body>
<ul id="mytags">
<li>Tag1</li>
</ul>
</body>
</html>
(get tag-it.js file from [here][1])
and this is the PHP file:
<?php
header('Content-type: application/json');
$q = $_GET["search"];
//check $q, get results from your database and put them in $arr
$arr[] = 'tag1';
$arr[] = 'tag2';
$arr[] = $q;
echo json_encode($arr);
?>
None of these answers worked as is for me, so I thought I would come back and post my code that does work.
var tagThis = $(".tagit");
tagThis.tagit({
tagSource: function(search, showChoices) {
$.ajax({
url: "/tags/search",
data: { search: search.term },
dataType: "json",
success: function(data) {
var assigned = tagThis.tagit("assignedTags");
var filtered = [];
for (var i = 0; i < data.length; i++) {
if ($.inArray(data[i], assigned) == -1) {
filtered.push(data[i]);
}
}
showChoices(filtered);
}
});
}
});
This code assumes the URL returns a JSON encoded string (an array of strings). It will then filter out any tags that have already been selected in the input. So they aren't repeated in the list. Otherwise, this works for me.
Thanks to the others for sending me on the right path.
tagSource has been depreciated.
Just use:
<script>
$(document).ready(function(){
$("#tagit").tagit({
autocomplete: {
source: "your-php-file.php",
}
});
});
</script>
You can add all the attributes to this:
<script>
$(document).ready(function(){
$("#tagit").tagit({
allowSpaces: true,
singleFieldDelimiter: ';',
allowDuplicates: true,
autocomplete: {
source: "your-php-file.php",
}
});
});
</script>
You should remove your availableTags, as you are overloading tagSource, which is used as source for the autocompletion.
Also that may be a typo, but it "return", and not "eturn".
Edit:
I think the problem is that the function you provided to tagSource doesn't seems to return anything. However my javascript knowledge seems to end here :/
I think that you can overwrite the autocomplete method from jquery UI :
$('.tags ul').tagit({
itemName: 'question',
fieldName: 'tags',
removeConfirmation: true,
//availableTags: ["c++", "java", "php", "javascript", "ruby", "python", "c"]
allowSpaces: true,
// tagSource: ['foo', 'bar']
tagSource: function () {
$.ajax({
url: "/autocomplete_tags.json",
dataType: "json",
data: {
term: 'ruby'
},
success: function (data) {
console.log(data);
return data;
}
});
},
autocomplete: {
delay: 0,
minLength: 2,
source: this.tagSource()
}
});
Just to add
Assuming your script page looks like
<script>
$(document).ready(function(){
$("#myULTags").tagit({
allowSpaces: true,
singleFieldDelimiter: ';',
allowDuplicates: true,
autocomplete: {
source: "searchtag.php",
}
});
});
</script>
Your simple php page if you are fetching values from database would look like
<?php $link = mysqli_connect("localhost","root","dbpassword","dbname") or die("Couldn't make connection."); ?>
<?php
$q = strtolower($_GET["term"]);
if (!$q) return;
header('Content-type: application/json');
$query_tags = mysqli_query($link,"SELECT TagName FROM `tagstable` WHERE `TagName` LIKE '%".$q."%' LIMIT 10");
$items = array(); // create a variable to hold the information
while ($row = mysqli_fetch_array($query_tags)){
$items[] = $row['TagName']; // add the row in to the results (data) array
}
echo json_encode($items);
?>
Regards

Categories