Live Search get multiple fields - php

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.

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

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.

jQuery UI Autocomplete not working with codeigniter

I'm trying to get a field on my view to autocomplete with values from a database but can't seem to figure out what is going wrong....
In my view I have the following script:
$(document).ready(function() {
$(function() {
$( "#searchQuestion" ).autocomplete({
source: function(request, response) {
$.ajax({ url: "<?php echo site_url('contentmanagement/suggestions'); ?>",
data: { term: $("#searchQuestion").val()},
dataType: "json",
type: "POST",
success: function(data){
response(data);
}
});
},
minLength: 2
});
});
});
Within my contentmanagement controller I have the "suggestions" function:
function suggestions() {
$this->load->model('onlinehelp');
$term = $this->input->post('term', TRUE);
if (strlen($term) < 2)
break;
$rows = $this->onlinehelp->GetAutocomplete($term);
$keywords = array();
foreach ($rows as $row)
array_push($keywords, $row->question);
echo json_encode($keywords);}
And Finally within my model I have the follow function -
function GetAutocomplete($term) {
$this->db->select('question');
$this->db->like('question',$term, 'both');
$query = $this->db->get('question');
return $query->result();
}
The query above is the equivalent to "SELECT question FROM question WHERE question LIKE %$term%.
Can anyone see where I am going wrong with this??
You might be getting a 500 Internal Server Error caused by CSRF protection being enabled. If so, every POST request must contain a CSRF value. You have a few options:
1. Include the CSRF value in your data using $this->input->cookie('your_csrf_name');
2. Perform GET request instead of POST.
Use $this->input->get('term', TRUE); in your controller. Remember to sanitize and validate the value.
3. Disable CSRF protection. Not recommended.
This works with the CSRF enabled:
Use the jquery cookie plugin
<script type='text/javascript' src='<?php echo base_url(); ?>/js/lib/jquery.cookie.js'></script>
Then on your autocomplete thing:
<script type="text/javascript">
$(document).ready(function() {
$(function() {
$("#searchQuestion").autocomplete({
source: function(request, response) {
$.ajax({ url: "<?php echo site_url('contentmanagement/suggestions'); ?>",
data: { term: $("#searchQuestion").val(), ci_csrf_token: $.cookie("ci_csrf_token") },
dataType: "json",
type: "POST",
success: function(data){
response(data);
}
});
},
minLength: 2,
focus: function( event, ui ) {
$("#searchQuestion").val(ui.item.term);
return false;
}
})
.data("autocomplete")._renderItem = function( ul, item ) {
return $( "<li></li>" )
.data( "item.autocomplete", item )
.append( "<a>" + item.term + "</a>" )
.appendTo( ul );
};
});
});</script>

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