I'm using this jquery plugin : JQuery Autocomplete. Problem I'm getting json data but it's not appearing on the autocomplete list.
The JQuery code:
$( "#student-id" ).autocomplete({
source: function( request, response ) {
$.ajax({
url: "ajax/ajax_admin.php?auto_student=" + $( "#student-id" ).val(),
dataType:"json",
data: {
featureClass: "P",
style: "full",
maxRows: 12,
name_startsWith: request.term
},
success: function( data ) {
response( $.map( data.students, function( item ) {
return {
label: item.id +" , "+ item.name,
value: item.id
}
}));
}
});
},
minLength: 2,
open: function() {
$( this ).removeClass( "ui-corner-all" ).addClass( "ui-corner-top" );
},
close: function() {
$( this ).removeClass( "ui-corner-top" ).addClass( "ui-corner-all" );
}
});
The PHP Script is :
public function load_ajax_student_list($val)
{
$val = "%".$val."%";
$stmt = $this->conn->prepare("select * from student where studentAiubId like :value limit 0,5");
$stmt->bindValue(':value', $val);
$stmt->execute();
if($stmt->rowCount() < 1)
echo "";
else
{
$result = $stmt->fetchAll();
$output = array();
foreach($result as $row)
{
if($row['mname']=="")
$name = $row['fname']." ".$row['lname'];
else
$name = $row['fname']." ".$row['mname']." ".$row['lname'];
$data["name"] = $name;
$data["id"] = $row['studentAiubId'];
$output["students"][] = $data;
}
echo json_encode($output);
}
}
If the call goes like this: ajax/ajax_admin.php?auto_student=10
The produced data from PHP script is :
{
"students": [
{"name":"Moh Mamun Sardar","id":"10-15987-1"},
{"name":"Rehan Ahmed","id":"10-12451-2"},
{"name":"Abid Hassan","id":"10-15412-1"},
{"name":"Abir Islam","id":"10-11245-1"}
]
}
But Nothing showing on autocomplete. What I'm doing wrong?
try something like this
$.map( data.students, function(item ) {
return {
label: item.name,
value: item.id
});
it is minlength not minLength see casing
You have forgotten the "appendTo" property. In this propery you have to specify the selector of the element you wish the information to be appended to like this
appendTo: '.class' or appendTo: '#id'
You have to add this property to the initialization of the autocomplete as a sibling of source and etc ...
Related
I am trying to populate multiple fields with jQuery from user input in one form but I'm not getting any result in JSON. Can anyone spot what the problem is?
$('#countryname_1').autocomplete({
source: function( request, response ) {
$.ajax({
url : 'search.php',
dataType: "json",
data: {
name_startsWith: request.term,
type: 'country_table',
row_num : 1
},
success: function( data ) {
response( $.map( data, function( item ) {
var code = item.split("|");
return {
label: code[0],
value: code[0],
data : item
}
}));
}
});
},
autoFocus: true,
minLength: 0,
select: function( event, ui ) {
var names = ui.item.data.split("|");
$('#country_no_1').val(names[1]);
$('#phone_code_1').val(names[2]);
$('#country_code_1').val(names[3]);
}
});
The PHP I'm using to query the database
require ($_SERVER['DOCUMENT_ROOT'].'/config/dbconnect.php');
if(isset($_POST['type']) == 'country_table'){
$result = $db->prepare("SELECT firstname, department FROM users where firstname LIKE '".strtoupper($_POST['name_startsWith'])."%'");
$data = array();
while ($row->fetch(PDO::FETCH_ASSOC)){{
$name = $row['firstname'].'|'.$row['department'].'|'.$row_num;
array_push($data, $name);
}
echo json_encode($data);
}
}
Nothing appears in the form and Chrome shows that no data is being passed back
I'm trying to fill an autocomplete with the result of a mysql query and the options never show up, but I'm getting the json response correctly. I tried to change the z-index in my master css file and in the jquery-ui.css but it doesn't work.
This is my jquery function.
$('#tasklist').autocomplete({
source: function(request, response) {
$.ajax({
url: 'pruebaproy.php',
type: 'GET',
data: {term: request.term},
success: function(data) {
response( $.map( data, function ( item ) {
return item;
}));
}
});
},
minLength: 2,
focus: function( event, ui ) {
$('#tasklist').val( ui.item.nombre );
return false;
}
});
This is my PHP function that does the mysql query:
public function showTasks($term) {
include 'Conexion.php';
$conectar = new Conexion();
$arr_res = array();
$consulta = "SELECT * FROM Actividades WHERE nombre LIKE '%".$term."%'";
if($stmt = $conectar->open()->query($consulta)) {
while($row = $stmt->fetch_array(MYSQL_ASSOC)) {
$task['id'] = utf8_encode($row['idActividades']);
$task['nombre'] = utf8_encode($row['nombre']);
$task['cat'] = utf8_encode($row['parteAsoc']);
array_push($arr_res, $task);
}
echo json_encode($arr_res);
}
$stmt->close();
}
And I call this function in my 'pruebaproy.php'
include('Proyecto.class.php');
$proyect = new Proyecto();
if(isset($_GET['term'])) {
$proyect->showTasks(trim(strip_tags($_GET['term'])));
}
Try changing the datatype to 'json' on the ajax request, and place some alerts along the code to validate if you're getting there (for example inside the success).
$( "#city" ).autocomplete({
source: function( request,response ) {
$.ajax({
url: "dtautocomplete.php",
dataType: "json",
data: {term: request.term},
success: function( data) {
response( data.myData );
}
});
},
select: function( ) {
$( "#city" ).attr("selectflag","1");
}
});
Php side
<?php
//die("sleeeeeeeeeeeeeeeppppppppppppppppppppppppppppppppppppppppppppppp");
$term=$_GET['term'];
$query="SELECT `RegionName`, `CenterLatitude`,`CenterLongitude` FROM `regioncentercoordinateslist` WHERE `RegionName` LIKE '".$term."%' AND `RegionName` NOT LIKE '%type%' LIMIT 10";
// echo $query;
$data= mysql_query($query);
//var_dump($data);die();
$count=0;
while($dat=mysql_fetch_array($data))
{
if($count>12)
{break;}
$tmpt1=$dat['CenterLatitude'];
$tmpt2=$dat['CenterLongitude'];
$tmpt=$tmpt1.",".$tmpt2;
$city[] = array(
'label' =>$dat['RegionName'],
'value' => $tmpt
);
$city2[] = $dat['RegionName'];
$options['myData'][] = array(
'label' =>$dat['RegionName'],
'value' => $dat['RegionName']
);
$name=$dat['RegionName'];
// echo "<div>$name</div>";
$count++;
}
echo json_encode($options);
//flush();
?>
Try utilizing ._renderItem . See Custom data and display "viewsource"
$('#tasklist').autocomplete({
source: function(request, response) {
$.ajax({
url: 'pruebaproy.php',
type: 'GET',
data: {term: request.term},
success: function(data) {
response( $.map( data, function ( item ) {
return item
})
}
});
},
minLength: 2,
focus: function( event, ui ) {
$('#tasklist').val( ui.item.nombre );
return false;
}
}).autocomplete( "instance" )._renderItem = function( ul, item ) {
return $( "<li>" )
.append( "<a>" + item.id + "<br>" + item.cat + "</a>" )
.appendTo( ul );
};
});
<head>
<meta charset="utf-8">
<title>jQuery UI Autocomplete - Default functionality</title>
<link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
<script>
$(function() {
var availableTags = [
"ActionScript",
"AppleScript",
"Asp",
"BASIC",
"C",
"C++",
"Clojure",
"COBOL",
"ColdFusion",
"Erlang",
"Fortran",
"Groovy",
"Haskell",
"Java",
"JavaScript",
"Lisp",
"Perl",
"PHP",
"Python",
"Ruby",
"Scala",
"Scheme"
];
$("#tags").autocomplete({
source: availableTags
}).autocomplete("instance")._renderItem = function(ul, item) {
console.log(ul, item)
return $("<li>")
.append("<b style=color:orange;>" + item.label + "</b>")
.appendTo(ul);
};
});
</script>
</head>
<body>
<div class="ui-widget">
<label for="tags">Tags:</label>
<input id="tags">
</div>
</body>
I have this live search and it works perfectly. What i want to do is I want to get another field. Aside of fetching indcator name i also want to get its ID by assigning it to another input type once I clicked the indicatorname using live search.
Heres the Script :
<script type="text/javascript">
$(document).ready(function() {
$('#indicatorname').autocomplete({
source: function( request, response ) {
$.ajax({
url : 'ajax.php',
dataType: "json",
data: {
name_startsWith: request.term,
type: 'indicatorname'
},
success: function( data ) {
response( $.map( data, function( item ) {
return {
label: item,
value: item
}
}));
}
});
},
autoFocus: true,
selectFirst: true,
minLength: 0,
focus : function( event, ui ) {
$('#indicatorname').html(ui.item.value);
},
select: function( event, ui ) {
$('#indicatorname').html(ui.item.value);
},
open: function() {
$( this ).removeClass( "ui-corner-all" ).addClass( "ui-corner-top");
},
close: function() {
$( this ).removeClass( "ui-corner-top" ).addClass( "ui-corner-all" );
}
});
$('#slider').rhinoslider({
effect: 'transfer'
});
});
</script>
Heres the ajax.php :
<?php
$connection = pg_connect("host=localhost dbname=brgy_profiler
user=postgres password=password");
if (!$connection)
{
echo "Couldn't make a connection!";
}
?>
<?php
if($_GET['type'] == 'indicatorname'){
$result = pg_query("SELECT cindicatordesc,nindicatorid from
tbl_indicators where cindicatordesc LIKE
'%".$_GET['name_startsWith']."%'");
$data = array();
while ($row = pg_fetch_array($result))
{
array_push($data, $row['cindicatordesc']);
}
echo json_encode($data);
}
?>
Here's my tbl_indicator :
How can i get also the nindicatorid field and get it together with cindicatordesc using ajax live search?
Note: Only cindicatordesc will be displayed and nindicatorid will be save in an input type.
Not a problem. You can add additional data attributes in your Auto-complete select return as,
$('#indicatorname').autocomplete({
source: function( request, response ) {
...........
success: function( data ) {
response( $.map( data, function( itemList ) {
return {
label: itemList.label,
value: itemList.value,
extraField : itemList.extraField
}
}));
So, Only change you need to accommodate is the Server side where you need to send the extra values to the Auto-complete AJAX.
And , On select event you can fetch the value as ui.item.extraField.
Here is a Sample Demo of using multiple attributes. Although it is not same as you have done, the inner logic is the same.
I trying to create a multifunctional search bar, where one can not only look for cities (using Geonames) but also using the same input field for finding signed up users (using my MYSQL table.
I managed to achieve both seperately, however I couldn't manage to merge the code together.
The JQuery code for the geoname autocomplete:
$(function() {
$( "#top_search_field" ).autocomplete({
source: function( request, response ) {
$.ajax({
url: "http://api.geonames.org/searchJSON?username=dummie",
dataType: "jsonp",
data: {
featureClass: "P",
style: "full",
country: "AT",
maxRows: 12,
name_startsWith: request.term
},
success: function( data ) {
response( $.map( data.geonames, function( item ) {
return {
label: item.name + (item.adminName1 ? ", " + item.adminName1 : "") + ", " + item.countryName,
value: item.name
}
}));
}
});
},
minLength: 2,
select: function (event, ui) {
var selectedObj = ui.item;
jQuery("#top_search_field").val(selectedObj.value);
return false;
},
open: function () {
jQuery(this).removeClass("ui-corner-all").addClass("ui-corner-top");
},
close: function () {
jQuery(this).removeClass("ui-corner-top").addClass("ui-corner-all");
}
});
});
The code for grabbing the users from the table:
$(function() {
$( "#top_search_field" ).autocomplete({
source:'php_includes/search.php',
minLength: 2,
open: function () {
jQuery(this).removeClass("ui-corner-all").addClass("ui-corner-top");
},
close: function () {
jQuery(this).removeClass("ui-corner-top").addClass("ui-corner-all");
}
})
});
search.php
include_once("db_connect.php");
$stmt = $db_connect->query("SELECT user_auth, first_name, last_name, avatar FROM users WHERE (first_name LIKE '%".$_REQUEST['term']."%' OR last_name LIKE '%".$_REQUEST['term']."%') ");
while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$results[] = array('label' => utf8_encode($row['first_name'].' '. $row['last_name'] ) );
}
echo json_encode($results);
What is the best way to merge the codes together and make it possible to look for both cities and users?
You need to do a service for getting information from multiple service, combine them and respond to your autocomplete result. Let say you have a service called advanced_search.php. In this file;
<?php
$keyword = $_GET["keyword"];
$result = array();
$usersReturnedFromService = getUsersFromService($keyword); // Get users from service by using curl
foreach ($usersReturnedFrom as $user) {
array_push(array("type" => "user", "value" => $user));
}
$geoNamesReturnedFromService = getGeoNamesFromService($keyword); // Get geonames from service by using curl
foreach ($geoNamesReturnedFromService as $geoname) {
array_push(array("type" => "geoname", "value" => $geoname));
}
// When you sort, result will mixed
function compareArr($a, $b){
$ad = strtotime($a['value']);
$bd = strtotime($b['value']);
return ($ad-$bd);
}
usort($result, 'compareArr');
echo json_encode($result);
And in js side;
$(function() {
$( "#top_search_field" ).autocomplete({
source: function( request, response ) {
$.ajax({
url: "advanced_search.php?keyword=" + request.term, // put other variables here. I have only put term
success: function( data ) {
response( $.map( data, function( item ) {
return {
label: item.value, // john
value: item.type + "|" + item.value // user|john
}
}));
}
});
},
minLength: 2,
select: function (event, ui) {
var selectedObj = ui.item;
jQuery("#top_search_field").val(selectedObj.value);
return false;
},
open: function () {
jQuery(this).removeClass("ui-corner-all").addClass("ui-corner-top");
},
close: function () {
jQuery(this).removeClass("ui-corner-top").addClass("ui-corner-all");
}
});
});
I am trying to make my autocomplete search work but when i try to get data from my json array it doesnt work. I am not so familiar with this, but this is how my code looks like. I think I know how the first file works but I don't get it how my "searchapi.php" is going to be wrote. And what is this $.map? Would be great if someone could explain :D Thank you
index.php:
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
<link rel="stylesheet" href="/resources/demos/style.css" />
<style>
.ui-autocomplete-loading {
background: white url('images/ui-anim_basic_16x16.gif') right center no-repeat;
}
#city { width: 15em; }
</style>
<script>
$(function() {
function log( message ) {
$( "<div>" ).text( message ).prependTo( "#log" );
$( "#log" ).scrollTop( 0 );
}
$( "#city" ).autocomplete({
source: function( request, response ) {
$.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 ) {
return {
label: item.name,
value: item.name
}
}));
}
});
},
minLength: 2,
select: function( event, ui ) {
log( ui.item ?
"Selected: " + ui.item.label :
"Nothing selected, input was " + this.value);
},
open: function() {
$( this ).removeClass( "ui-corner-all" ).addClass( "ui-corner-top" );
},
close: function() {
$( this ).removeClass( "ui-corner-top" ).addClass( "ui-corner-all" );
}
});
});
</script>
searchapi.php
<?php
$host = "localhost";
$user = "root";
$pass = "";
$databaseName = "mydb";
$con = mysql_connect($host,$user,$pass);
$dbs = mysql_select_db($databaseName, $con);
$value = #$_POST['name_startsWith'];
$data = ("select name from column where name LIKE '".$value."'");
$result = mysql_query($data);
$dataArray = array();
while($array = mysql_fetch_assoc($result)){
$dataArray[] = $array;
}
echo json_encode($dataArray);
?>
The searchapi.php file purely queries your database for like entries based upon the string (name_startsWith) being sent by the autocomplete function.
The $.map is a jQuery method for translating "all items in an array or object to new array of items." You can read about it here: http://api.jquery.com/jQuery.map/