Jquery autocomplete with label and links - javascript

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.

Related

How to map a complex nested json to jquery autocomplete format?

How to map a complex nested json to jquery autocomplete format? I tried to map my custom json to the required jquery autocomplete format label, value, ... but my list is 'undefined'. This is my setup:
JSON:
{"data":[{"DT_RowId":"row_A6J851","accounts":{"code":"A6J851","name":"Peter Jackson"}},{"DT_RowId":"row_1D01Q14","accounts":{"code":"1D01Q14","name":"Earl Bundy"}}]}
Javascript:
$('#input-search').autocomplete({
source: function ( request, response ) {
$.ajax({
type: 'GET',
url: '/source.php',
dataType: "json",
success: function( data ) {
response( $.map( data.data.accounts, function( value, key ) {
return {
label: value.name,
value: value.name,
id: value.code
}
}));
}
});
},
create: function() {
$(this).data('ui-autocomplete')._renderItem = function (ul, item) {
return $( "<li></li>" )
.append( "<a>" + item.label + "</a>" )
.appendTo( ul );
};
}
});
It looks like from your data example that you are not iterating over the nested accounts array, but rather the data array. Try something like this:
$('#input-search').autocomplete({
source: function ( request, response ) {
$.ajax({
type: 'GET',
url: '/source.php',
dataType: "json",
success: function( data ) {
var results = [];
$.each(data.data, function(d){
var mapped = $.map(d.accounts, function( value, key ) {
return {
label: value.name,
value: value.name,
id: value.code
};
})
results = results.concat(mapped);
});
response(results);
}
});
},
create: function() {
$(this).data('ui-autocomplete')._renderItem = function (ul, item) {
return $( "<li>" )
.append( "<span>" + item.label + "</span>" )
.appendTo( ul );
};
}
});

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

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

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

Why jQuery autocomplete select not work?

When I input 5 in the customer_code input area. It list the values.The problem is that when I select an entry, the 'id' value should show in the customer_name area.But it didn't!
[{"id":"5","code":"code005","name":"\u9867\u5ba2\u540d005"},{"id":"15","code":"code015","name":"\u9867\u5ba2\u540d015"},]
the json return by php is like above.and
$(function() {
$( "#customer_code" ).autocomplete({
source: function( request, response ) {
$.ajax({
url: "/management/order/auto",
dataType: "json",
data: {code: request.term},
success: function(data) {
var suggestions = [];
$.each(data, function(i, val) {
suggestions.push({
label: val.code,
// label: val.name,
});
});
response( suggestions );
},
});
},
select: function(e, ui) {
alert(ui.item.name);
// $('#customer_name').val(ui.item.name);
// $('#customer_name').val(ui.item.value.name);
// return false;
},
});
});
my html page is like this
<?php echo Form::input('customer_name', Arr::get($basic, 'customer_name'), array('id' => 'customer_name')); ?>
<?php echo Form::input('customer_code', Arr::get($basic, 'customer_code'), array('id' => 'customer_code')); ?>
The select callback is currently part of the settings for the $.ajax() request, which won't use it:
// ...
$.ajax({
url: "/management/order/auto",
// ...
success: function (data) {
// ...
},
select: function (e, ui) {
// ...
}
});
// ...
It should instead be part of the options for .autocomplete(), outside of the function for source.
$( "#customer_code" ).autocomplete({
source: function( request, response ) {
$.ajax({
url: "/management/order/auto",
// ...
success: function () {
// ...
}
});
},
select: function (e, ui) {
// ...
}
})

CKeditor populate dialog select with Ajax

I am trying to populate my CKeditor dialog selectbox with ajax. The following is from my plugin.js file:
...
{
type : 'select',
id : 'style',
label : 'Style',
setup : CKEDITOR.ajax.post( '.../ckeditor/plugins/simpleLink/ajax.php', JSON.stringify( { foo: 'bar' } ), 'application/json', function( data ) {
console.log( data);
}),
items : [ ['--- Select something ---', 0] ],
commit : function( data )
{
data.style = this.getValue();
}
}
...
The ajax output looks like this:
["Basketball","basketball"],["Baseball","baseball"],["Hockey","hockey"]
I am really wondering how to get the output INTO the "items". From my point of view I tried everything.
Can someone help me?
CKEditor select widgets have an 'add' function you can call to populate them. You can call it from an 'onLoad' function, if you add one:
{
type: 'select',
id: 'myselect',
label: 'The select will be empty until it is populated',
items: [ ],
onLoad: function(api) {
widget = this;
$.ajax({
type: 'GET',
url: 'path/to/your/json',
dataType: 'json',
success: function(data, textStatus, jqXHR) {
for (var i = 0; i < data.length; i++) {
widget.add(data[i]['label'], data[i]['value']);
}
},
error: function(jqXHR, textStatus, errorThrown) {
console.log('ajax error ' + textStatus + ' ' + errorThrown);
},
});
},
},
Found a workaround. For anyone having the same problem - here is my way of solving it:
plugin.js:
This code before "CKEDITOR.plugins.add( 'PLUGINNAME', {..."
jQuery.extend({
getValues: function(url) {
var result = null;
$.ajax({
url: url,
type: 'get',
dataType: 'json',
async: false,
success: function(data) {
result = data;
}
});
return result;
}
});
var results = $.getValues('.../ckeditor/plugins/PLUGINNAME/ajax.php');
This is the code for the select box
{
type : 'select',
id : 'style',
label : 'Style',
setup : '',
items : results,
commit : function( data )
{
data.style = this.getValue();
}
}

Categories