jQuery search box auto complete - php

I want to create a auto complete search which get inputs and prints result in a div.When i run my php code it gives correct results but it does not work with jquery, i can not print results which is about users input.My codes are like this,
My codes;
$('#search').on('input',function(e){
$('#search').autocomplete({
source: function( request, response ) {
$.ajax({
url : 'complete.php',
dataType: "json",
data: {
name1: request.term,
type: 'name'
},
success: function( data ) {
response( $.map( data, function( item ) {
return {
label: item,
value: item
}
}));
$("#showname").append(html);
}
});
},
autoFocus: true,
});
});
My Php Codes;
$name=$_POST['name1'];
$i=mysqli_query($con,"Select * from users where name like '".$name1."%'");
$data = array();
while($m=mysqli_fetch_assoc($i)){
array_push($data, $m['name']);
}
echo json_encode($data);
How can i search and print results according to user input ?
Thanks...

Use
success: function( data ) {
for (i=0;i<data.length;i++) {
$("#showname").append(data[i] + '<br>');
}
}
to add it to your div. Add your own markup to your liking.

Related

Problem with json data source on ui autocomplete

I have a problem with my code. I receive data via ajax and it works, but the problem is that when I try to search for an element and all the elements appear so the search does not work properly.
JS code :
let marque_id =$("#marque_id").val();
$( "#grp_name" ).autocomplete({
source: function( request, response ) {
$.ajax({
url:"abonne/ajax_get_grp_autorisation",
method:"POST",
dataType: "json",
data: {
marque_id : id_marque
},
success: function( data ) {
response( data );
console.log(data);
}
});
},
select: function (event, ui) {
// Set selection
$('#grp_name').val(ui.item.label); // display the selected text
$('#id_grp_selected').val(ui.item.id); // save selected id to input
return false;
}
});
PHP code :
$data = array();
while($line = mysqli_fetch_object($liste_grp) ){
$data[] = array("label"=>$line->grp_nom,"value"=>$line->grp_nom ,"id"=>$line->groupement_id);
}
echo json_encode($data);
result
you should send the text you are searching for to ajax request so your autocomplete function should be
let marque_id =$("#marque_id").val();
$( "#grp_name" ).autocomplete({
source: function( request, response ) {
$.ajax({
url:"abonne/ajax_get_grp_autorisation",
method:"POST",
dataType: "json",
data: {
marque_id : id_marque ,
term: request.term
},
success: function( data ) {
response( data );
console.log(data);
}
});
},
select: function (event, ui) {
// Set selection
$('#grp_name').val(ui.item.label); // display the selected text
$('#id_grp_selected').val(ui.item.id); // save selected id to input
return false;
}
});
request.term is your search text and in your example it is group text
and also you need to modify your mysql query and add condition (like)
for example
$rs = mysql_query("SELECT * FROM table WHERE colum LIKE '%" . $_POST['term'] . "%'");
and finally you can check https://jqueryui.com/autocomplete/#remote-jsonp
I would advise the following jQuery:
$( "#grp_name" ).autocomplete({
source: function(request, response) {
$.ajax({
url:"abonne/ajax_get_grp_autorisation",
method:"POST",
dataType: "json",
data: {
marque_id: request.term
},
success: function( data ) {
console.log(data);
response(data);
}
});
},
select: function (event, ui) {
// Set selection
$('#grp_name').val(ui.item.label); // display the selected text
$('#id_grp_selected').val(ui.item.id); // save selected id to input
return false;
}
});
This is a small change. This will send the request.term to your PHP Script. For example, if the user types "gro", this will be sent to your script and would be accessed via:
$_POST['marque_id']
This would assume your SQL Query is something like:
$stmt = $mysqli->prepare("SELECT * FROM table WHERE column LIKE '?%'");
$stmt->bind_param("s", $_POST['marque_id']);
$stmt->execute();
$liste_grp = $stmt->get_result();
$data = array();
while($line = $liste_grp->fetch_assoc()) {
$data[] = array(
"label" => $line['grp_nom'],
"value" => $line['grp_nom'],
"id" => $line['groupement_id']
);
}
$stmt->close();
header('Content-Type: application/json');
echo json_encode($data);
This uses the MySQLi Prepared Statement, and will help prevent SQL Injection. I also included the JSON Header as good practice. The result of search "gro" would be something like:
[
{
"label": "GROUPE DATAPNEU TEST",
"value": "GROUPE DATAPNEU TEST",
"id": 1
}
];
Thanks guys i found a solution it works better
i used tokeninput with many options
http://loopj.com/jquery-tokeni
$.ajax({
url:"ajax_get_societe_authorisation",
method:"POST",
scriptCharset: "iso-8859-1",
cache: false,
dataType: "json",
data: {
marque_id : id_marque
},
success: function( data ) {
console.log(data);
$("#soc_name").tokenInput(data
,{
tokenLimit: 1,
hintText: "Recherche une société par son nom",
noResultsText: "Aucune société trouvé",
searchingText: "Recherche en cours ...",
onAdd: function (data) {
$("#soc_id").val(data.id);
},
onDelete: function (item) {
$("#soc_id").val("");
}
}
);
}
});

Autocomplete Field with jQuery

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

php code to store id of selected value from autocomplete textbox

below is my autocomplete textbox code..
code is working fine..
But I also need to store id of selected value in hidden textbox ..
FOR EX =
there are 2 values coming in my auto textbox
id societyname
7 raj
15 lucky
ok if i select raj from above value then display id of raj ie : 7 in hidden textbox
plz any one help me.
Autocomplete textbox
<input id="society_name" name="society"/>
<input type="hidden" id="society_name" name="societyid"/>
In ajax.php
if($_GET['type'] == 'society'){
$result = mysql_query("SELECT society FROM societymaster where society LIKE '".strtoupper($_GET['name_startsWith'])."%'");
$data = array();
while ($row = mysql_fetch_array($result)) {
array_push($data, $row['society']);
}
echo json_encode($data);
}
auto.js
$('#society_name').autocomplete({
source: function( request, response ) {
$.ajax({
url : 'ajax.php',
dataType: "json",
data: {
name_startsWith: request.term,
type: 'society'
},
success: function( data ) {
response( $.map( data, function( item ) {
return {
label: item,
value: item
}
}));
}
});
},
autoFocus: true,
minLength: 0
});
Use the val() function on the input pass the id from the ajax results
$('#society_name').val(data.id);
Updated code:
php:
if($_GET['type'] == 'society'){
$result = mysql_query("SELECT id,society FROM societymaster where society LIKE '".strtoupper($_GET['name_startsWith'])."%'");
$data = array();
while ($row = mysql_fetch_array($result)) {
array_push($data,$row);
}
echo json_encode($data);
}
js:
$('#society_name').autocomplete({
source: function( request, response ) {
$.ajax({
url : 'ajax.php',
dataType: "json",
data: {
name_startsWith: request.term,
type: 'society'
},
success: function( data ) {
$('#society_name').val(data[0].id);
response( $.map( data, function( item ) {
return {
label: item,
value: item
}
}));
}
});
},
autoFocus: true,
minLength: 0
});
If you need IDs then fetch them from DB and return in ajax call (I guess this is the ID you are talking about).
From this point you can use something like this, that you cache the returned results in e.g. associative array:
$arr[value] = id;
and if user selects one of the values you can get the corresponding ID.
That's one method I guess.
BTW.
some tips for the future:
1. The id's fields should have unique values.
2. You should consider protecting your query from sql attacks. Here you do not even escape the string which is given by the user.
3. As far as I remember the mysql is obsolete so try to use mysqli instead.
ajax.php
if($_GET['type'] == 'society'){
// try to switch to mysqli. You can also consider prepare statements.
$result = mysql_query("SELECT id, society FROM societymaster where society LIKE '".mysql_real_escape_string(strtoupper($_GET['name_startsWith']))."%'");
$data = array();
while ($row = mysql_fetch_array($result)) {
array_push($data, $row);
}
// mysql_fetch_array returns indexed array so we should get JSON string like: "[['id1', 'value1'], ['id2', 'value2'], ...]"
echo json_encode($data);
}
.js file
$.arr = [];
$('#society_name').autocomplete({
source: function( request, response ) {
$.ajax({
url : 'ajax.php',
dataType: "json",
data: {
name_startsWith: request.term,
type: 'society'
},
success: function( data ) {
// clear cache array and fill it with information about the new results (societies and corresponding ids)
$.arr = [];
$.each(data, function (idx, item) {
$.arr[item[1]] = item[0];
});
$('#society_name').val(data[0].id);
response( $.map( data, function( item ) {
return {
label: item,
value: item
}
}));
}
});
},
autoFocus: true,
minLength: 0
});
// catch an event when the autocomplete closes and get id for selected society name
$("#tags").on("autocompleteclose", function() {
// close event does not provide object data so we must fetch it again
var selectedValue = $("#tags").val();
var id = $.arr[selectedValue];
// now you can set this ID as the value of your hidden input
});

Live Search get multiple fields

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.

jQuery Autocomplete ajax does not create dropdown of selections from php

I'm struggling, as a newbie, with an Autocomplete that does not create a dropdown with selection options. The full code has 2 stages - the user selects a country via radio buttons, then starts an Autocomplete to select a state/province. Per Firefox, the country code and the state typing POST to the php script, the query executes correctly using both country and state script elements, a response is constructed. Autocomplete does not create a dropdown with selections. Firefox gives a parse error message and improper JSON message from my error: alert. When I put the response elements in JSONlint, it says the element is valid JSON. Firefox shows correct content in query arrays as I change country and change the state typing. I have copied the success function and the select option, but I'm unsure about them. The alert in the select option does not trigger. Help would be appreciated to get a populated dropdown. Here's the code:
jQuery Autocomplete:
$("#stateProvince").autocomplete
({
source: function( request, response )
{
$.ajax(
{
url: "getStateProvince.php",
data: {
term: request.term,
country: $('input[name=country]:checked').val(),
},
type: "POST",
dataType: "json",
error: function(x,y,z) {
alert(x+'\n'+y+'\n'+z);};
success: function( data )
{
response( $.map( data, function( item )
{
return{
label: item.label,
value: item.value
}
}));
}
});
},
minLength: 2,
select: function (event, ui) //is this select necessary? correct? return true or false?
{
alert('|' + ui.item + '|2nd');
$("#stateProvince").val(ui.item.value);
return;
}
});
selected php:
while ($row = mysql_fetch_array($fetch, MYSQL_ASSOC))
{
/* In each row, pull stateProvinceNameInEnglish and stateProvinceAbbreviation. */
$row_array['label'] = $row['stateProvinceNameInEnglish'];
$row_array['value'] = $row['stateProvinceAbbreviation'];
array_push($return_arr,$row_array);
}
}
/* Toss back state or province results as a json encoded array. */
echo json_encode($return_arr);
Have you tried it like this :
public function echoPhpArrayForAutocomplete(){
foreach($yourArray as $row){
$string .= '{';
$string .= '"label" : "'.$row['stateProvinceNameInEnglish'].'",';
$string .= '"value" : "'.$row['stateProvinceAbbreviation'].'",';
$string .= '"additionlInfo" : "'.$row['additionalInfo'].'"';
$string .= '},';
}
echo rtrim($string, ',');
}
Than you create you array like this in the
<script>
var arrayFromPhp = [ <?php echoPhpArrayForAutocomplete(); ?> ];
</script>
Than you make your input to show the drop down on keyup and give it the arrayw you want like this:
$('#stateProvince').live('keyup.autocomplete',function(){
$input = $(this);
$input.autocomplete({
minLength: 0,
source: arrayFromPhp , // Array with object describing the keywords. Defined with php in the view file
}).data( "autocomplete" )._renderItem = function( ul, item ) {
return $( "<li></li>" )
.data( "item.autocomplete", item )
.append( "<a>"+item.label+"</a>" )
.appendTo( ul )
.bind();
}
});
You may even put the 'additionInfo' to .append( ""+item.label+"" ) like this
.append( "a tag"+item.additionInfo+" close a tag" ) and it will show that in the dropdown... I don't know if i helped but i am at work this is the most time i could spare right now... If this did not solve it i would be glad to help later. Regards.
jQuery:
$("#stateProvince").autocomplete({
source: function( request, response )
{
$.ajax({
url: "getStateProvince.php",
data: {
term: request.term,
country: $('input[name=country]:checked').val(),
},
type: "POST",
dataType: "json",
error: function(x,y,z) {
alert(x+'\n'+y+'\n'+z);
},
success: function( data )
{
response(data);//<== Change Here
}
});
},
minLength: 2,
select: function (event, ui){
alert('|' + ui.item + '|2nd');
$("#stateProvince").val(ui.item.value);
return;
}
});
PHP:
while ($row = mysql_fetch_array($fetch, MYSQL_ASSOC)){
$row_array['label'] = $row['stateProvinceNameInEnglish'];
$row_array['value'] = $row['stateProvinceAbbreviation'];
array_push($return_arr,$row_array);
}
echo json_encode($return_arr);

Categories