Autocomplete Field with jQuery - php

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

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("");
}
}
);
}
});

How to do jQuery autocomplete using an AJAX call to a PHP script?

I have the following jQuery code for the autocomplete,
$( "#text" ).autocomplete({
source: function( request, response ) {
$.ajax({
type: 'GET',
url: 'server.php',
dataType: 'json',
data: {
input: request.term
},
success: function(data) {
response( $.map(data, function(item) {
return {
label: item.Symbol + " - " + item.Name + " ( " + item.Exchange + " )"
}
}));
}
});
},
minLength: 1,
select: function( event, ui ) {
var symbol = ui.item.label.split(' ');
setTimeout(function() {
$('#text').val(symbol[0]);
},0);
}
});
Whenever a user enters a key in the textbox, an AJAX call is made to a PHP file. This PHP file will retrieve data from an API and update the suggestions list for the autocomplete feature?
I've got the following code in the PHP side,
<?php
if(!empty($_GET['term'])) {
$term = $_GET['term'];
$url = "http://dev.markitondemand.com/MODApis/Api/v2/Lookup/json?input=".$term;
$j_response = file_get_contents($url);
$j_response = json_decode($j_response);
print json_encode($j_response);
}
?>
For some reason, the autocomplete isn't working for me- what am I doing wrong here?
In the PHP, you are trying to use $_GET['term'], but in the JavaScript your variable is called input. Change the data object to use term not input:
data: {
term: request.term
},

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 search box auto complete

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.

Categories