How to get the unique value in autocomplete in php from mysqldatabase - javascript

How to get the unique value in autocomplete in php from mysqldatabase. and how do i get all values just like i have 3 values in autocomplete which same so i want only one in autocomplete but want to fetch the data of all. how do i do this ?
just like in picture i want 1 one php only but want the data from all the three values.
i am trying some thing like this
var citycode;
$('#countryname_1').autocomplete({
source: function( request, response ) {
$.ajax({
url : 'ajax.php',
dataType: "json",
method: 'post',
data: {
name_startsWith: request.term,
type: 'country_table',
row_num : 1
},
success: function( data ) {
response( $.map( data, function( item ) {
var code = item.split("|");
var len=code.length;
var co= code[0];
return {
label: code[0],
value: code[0],
data : item
}
}));
}
});
},
autoFocus: true,
minLength: 0,
select: function( event, ui ) {
var names = ui.item.data.split("|").length;
var dat = ui.item.data.split("|");
citycode=dat[0] ;
alert(citycode);
}
});

Related

Javascript If statement not working in autocomplete

I have the following Javascript code that works perfectly as far as the autocompleting as well as filling 5 additional input fields, based on the loaded array from MySQL in the type_code.php file.
The sixth element of the array val(names[6]) is filled with a database value of either Yes or No and I am trying to use this value to control whether an additional form field becomes readonly or readwrite at the front end.
It seems as if my if statement is badly formatted, as if I run the two lines of codes without the if everything works as expected.
// Autocomplete Invoice To from Code and sets ReadOnly/ReadWrite based on Editable field in Code record
$('#add_at_inv2_code1').autocomplete({
source: function( request, response ) {
$.ajax({
url : 'type_code.php',
dataType: "json",
method: 'post',
data: {
name_startsWith: request.term,
type: 'code_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("|");
$('#desc_at_inv2_code1').val(names[1]);
$('#add_at_inv2_code2').val(names[2]);
$('#add_at_inv2_client').val(names[3]);
$('#add_at_salesrep').val(names[4]);
$('#add_at_category').val(names[5]);
// Code that is not working
if($(val(names[6])) == "Yes") {
$('#add_at_inv2_client').prop('readonly',false);
$('#add_at_inv2_client').prop('disabled',false);
} else {
$('#add_at_inv2_client').prop('readonly',true);
$('#add_at_inv2_client').prop('disabled',true);
}
}
});
Can someone please help me structure this if statement correctly?
Thanks,
Adri
The val() method returns or sets the value attribute of the selected elements.
Note: The val() method is mostly used with HTML form elements.
Use
if(names[6] == "Yes")
instead of
if($(val(names[6])) == "Yes")
=========================================================================
<script type="text/javascript">
// Autocomplete Invoice To from Code and sets ReadOnly/ReadWrite based on Editable field in Code record
$('#add_at_inv2_code1').autocomplete({
source: function( request, response ) {
$.ajax({
url : 'type_code.php',
dataType: "json",
method: 'post',
data: {
name_startsWith: request.term,
type: 'code_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("|");
$('#desc_at_inv2_code1').val(names[1]);
$('#add_at_inv2_code2').val(names[2]);
$('#add_at_inv2_client').val(names[3]);
$('#add_at_salesrep').val(names[4]);
$('#add_at_category').val(names[5]);
// Code that is not working
if(names[6] == "Yes") {
$('#add_at_inv2_client').prop('readonly',false);
$('#add_at_inv2_client').prop('disabled',false);
} else {
$('#add_at_inv2_client').prop('readonly',true);
$('#add_at_inv2_client').prop('disabled',true);
}
}
});
</script>
Need following change in your code
// Code that is not working
if(names[6] == "Yes") //Change this if($(val(names[6])) == "Yes")
{
$('#add_at_inv2_client').prop('readonly',false);
$('#add_at_inv2_client').prop('disabled',false);
}
else
{
$('#add_at_inv2_client').prop('readonly',true);
$('#add_at_inv2_client').prop('disabled',true);
}

Jquery autocomplete only shows results after i type 4th letter on input

I have a input where a user inserts a city name, and then i call a method with onkeyup
function autocompleteCity(id){
console.log($('#'+id).val());
if($('#'+id).val().length >= 2){
var data = {
query: $('#'+id).val()
}
$.ajax({
url: location.origin + '/autocomplete/city',
headers: {
apiKey: APIKEY
},
type: "POST",
data: data,
dataType: "json",
async: true,
success: function (data) {
var cities = [];
for(var i=0;i<data.cities.length;i++){
cities.push(data.cities[i].city);
}
console.log(cities);
$('#'+id).autocomplete({
source: cities
});
},
error: function (err) {
console.log(err);
}
});
}
}
and html
<input id="placeTo" onkeyup="autocompleteCity('placeTo')" type="text" class="form-control input-lg not-dark" value="" placeholder="Select a drop city">
For example if i type "To" i get this on console.log(cities)
Array [ "Toulouse", "Toronto", "Torun", "Tours" ]
but the autocomplete doesn't show, until the user types "Toky"
is this normal? or am i doing something wrong?
For your ajax you just need to implement the source option and for the minimum number of characters a user must type there is the minLength option.
$( "#city" ).autocomplete({
source: function( request, response ) {
$.ajax( {
url: location.origin + '/autocomplete/city',
dataType: "json",
type: "POST",
headers: {
apiKey: APIKEY
},
data: {
q: request.term
},
success: function( data ) {
// Handle 'no match' indicated by [ "" ] response
response( data.length === 1 && data[ 0 ].length === 0 ? [] : data );
}
} );
},
minLength: 2,
select: function( event, ui ) {
log( "Selected: " + ui.item.label );
}
}):
Initialize a autocomplete with the minLength option specified.
$( ".selector" ).autocomplete({ minLength: 2 });
It will work

Cant push autocomplete selected value to global array in JavaScript

Im working on a project in which I have autocomplete with users list.
when I try to push autocomplete selected value to global array I get an empty list when I do console.info(usernames) outside autocomplete function.
var usernames=[];
$(document).ready(function(){
$(function(){
$( "#users" ).autocomplete({
source: function( request, response ) {
$.ajax({
type: "GET",
url: "getUserFromDb.php",
dataType: "json",
data: {
term: request.term
},
success: function( data ) {
response( data );
}
});
},
minLength: 2,
select: function(event,ui){
usernames.push(ui.item.value);
}
});
console.info(usernames);
});
});
soruce of autocomplete is returning correct list and select works as well, because if I do console.info(usernames) inside autocomplete select: the list will update when im selecting different values.
Since you needed an "answer", here we go. First off, your console.info has run as soon as the DOM is ready and obviously empty as the user names are pushed in later on, when you select options from autocomplete. Secondly, you are not re-logging usernames as and when it's populated. So, you have 2 options.
1) log usernames within the select function, such as:
select: function(event,ui) {
usernames.push(ui.item.value);
console.info(usernames);
}
2) Have a function that would do the job for you, such as:
select: function(event,ui) {
usernames.push(ui.item.value);
showMeUserNames();
}
function showMeUserNames() {
console.info(usernames);
}
So, your code may become:
var usernames=[];
$(function(){
$( "#users" ).autocomplete({
source: function( request, response ) {
$.ajax({
type: "GET",
url: "getUserFromDb.php",
dataType: "json",
data: {
term: request.term
},
success: function( data ) {
response( data );
}
});
},
minLength: 2,
select: function(event,ui) {
usernames.push(ui.item.value);
console.info(usernames);
// OR
// showMeUserNames();
}
});
});
function showMeUserNames() {
console.info(usernames);
}

jQuery UI Autocomplete: How to base on JSON data NOT name & Label

I've got an AJAX url that returns data in the following format:
[{ "product": "Zip a dee doo dah", "desc": "F oq nfp gd r exbiikr wblkjm yumdd xy voqgt d hjtk. As sr ywvgiyb iqoibgm akron slfudtq smabx gj awlbtp ji vb do prvhlqq. ", "type": "Doodahs", "price": "3.99"}]
I'm trying to get the auto-complete to be based on the "product" entry.
Here is my code. It sends the request like it should, but I can't seem to get the auto-complete to populate the value based on 'product'. I'm sure I'm overlooking something stupid, but I've been staring at this for a few hours and figured its time to see if someone can help ;-).
Thanks for your help!
$(document).ready(function() {
$( "input[type='text']" ).autocomplete({
source: function( request, response ) {
$.ajax({
dataType: "json",
type : 'POST',
data: 'q=' + prepareInput(this.element.attr('name') + '=' + request.term),
success: function(data) {
$('input.suggest-user').removeClass('ui-autocomplete-loading');
return $.map( data, function(item) {
var r = $.parseJSON(data);
return {
label: r['product'],
value: r['product']
};
});
},
error: function(data) {
$('input.suggest-user').removeClass('ui-autocomplete-loading');
}
});
},
minLength: 3
});
});
--------------- Still not working, but current code below ------------------------
$(document).ready(function() {
$( "input[type='text']" ).autocomplete({
source: function( request, response ) {
$.ajax({
dataType: "json",
type : 'POST',
data: 'q=' + prepareInput(this.element.attr('name') + '=' + request.term),
success: function(data) {
$('input.suggest-user').removeClass('ui-autocomplete-loading'); // hide loading image
return $.map( data, function(item) {
console.log(item['product']);
return {
label: item['product'],
value: item['product']
};
});
},
error: function(data) {
$('input.suggest-user').removeClass('ui-autocomplete-loading');
}
});
},
minLength: 3
});
Console.log is currently writing out the proper value, but the auto-complete still isn't popping up.
--- Working Code Below - Finally Got it Running. Thanks #Robert --------------
I was missing a number of things:
1) It needs to be an array, so I added [].
2) Apparently the format needs to be assigned to "response".
Now its working...
$(document).ready(function() {
$( "input[type='text']" ).autocomplete({
source: function( request, response ) {
$.ajax({
dataType: "json",
type : 'POST',
data: 'q=' + prepareInput(this.element.attr('name') + '=' + request.term),
success: function(data) {
$('input.suggest-user').removeClass('ui-autocomplete-loading'); // hide loading image
return $.map( data, function(item) {
response([{
label: item['product'],
value: item['product']
}]);
});
},
error: function(data) {
$('input.suggest-user').removeClass('ui-autocomplete-loading');
}
});
},
minLength: 3
});
So you have an error on this line:
var r = $.parseJSON(data);
Post the output of console.log(data); //add this line bellow your success call
And change this line var r = $.parseJSON(data); to var r = $.parseJSON(item);
You are missing a single quote at end
prepareInput(this.element.attr('name'))

Jquery autocomplete with label and links

I have jquery autocomplete working perfect for label and it's value.
$( "#search_name" ).autocomplete({
source: function(request, response) {
$.ajax({
url: "/ajax/fetch_search_suggestion",
dataType: "json",
type: "POST",
data: {
keyword: request.term
},
success: function(data) {
response( $.map( data, function( item ) {
return {
label: item.label
}
}));
}
})
}
});
PHP
while($search = $result->fetch()){
$link = '';
$link .= $search['cus_firstname'].' '.$search['cus_lastname'];
array_push($searchArray, array('label'=> $link, 'value' => $keyword));
}
array_push($searchArray, array('label'=>"Not Here? Click to add new", 'value' =>"http://www.google.com"));
If customer is not there, on click add new it should go to the google.com. How can I achieve this? Thanks.
I tried with adding:
select : function(event, ui) {
response( $.map( data, function( item ) {
return {
window.location = (ui.item.value);
return false;
}
}));
}
But, I am getting error.

Categories