jQuery Autocomplete ajax does not create dropdown of selections from php - 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);

Related

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

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