Jquery UI Autocomplete with JSON and Ajax

JQuery UI autocomplete with json and ajax

You can stick very much to the remote demo of jQuery UI's Autocomplete: http://jqueryui.com/resources/demos/autocomplete/remote-jsonp.html

To get your results into the autocompleted list, you need to put a object with a label and a value to the response parameter (which is actually a function) inside your ajax success function:

source: function( request, response ) {
$.ajax({
url: "fill_id.php",
data: {term: request.term},
dataType: "json",
success: function( data ) {
response( $.map( data.myData, function( item ) {
return {
label: item.title,
value: item.turninId
}
}));
}
});
}

But this will only work if you modify yor fill_id.php a bit:

// escape your parameters to prevent sql injection
$param = mysql_real_escape_string($_GET['term']);
$options = array();

// fetch a title for a better user experience maybe..
$db = new SQLite3('database/main.db');
$results = $db->query("SELECT distinct(turninId), title FROM main WHERE turninid LIKE '".$param."%'");

while ($row_id = $results->fetchArray()) {
// more structure in data allows an easier processing
$options['myData'][] = array(
'turninId' => $row_id['turninId'],
'title' => $row_id['title']
);
}

// modify your http header to json, to help browsers to naturally handle your response with
header('Cache-Control: no-cache, must-revalidate');
header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
header('Content-type: application/json');

echo json_encode($options);

Of course, when you don't have a title or anything in your table, you can also just leave your response as it is and repeat the id in your success callback. Important is, that you fill your response function in the autocomplete with a value/item pair:

// this will probably work without modifying your php file at all:
response( $.map( data, function( item ) {
return {
label: item,
value: item
}
}));

edit:
updated the reference link to the new jquery UI's autocomplete ui

jQuery UI Autocomplete not showing AJAX results

try:

 $("#tags").autocomplete({
minLength: 2,
source: function( request, response ) {
$.getJSON("http://forums.zybez.net/runescape-2007-prices/api/"+request.term, function(data){
var items = [];

$.each( data, function(key, val){
items.push(val);
});

console.log(items); // Shows correct results
response(items);
});
}
});

see: http://jsfiddle.net/4g3818rr/

How to use jQuery autocomplete with json file?

I fixed some syntax errors and then wrote up this example to really get you jump started.

$( function() { $.getJSON("http://neil.computer/stack/beta.json", function(data) {  autoComplete = [];  for (var i = 0, len = data.length; i < len; i++) {   autoComplete.push(data[i].name + ", " + data[i].iata);  }  $( "#tags" ).autocomplete({   source: autoComplete  }); });});
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css"><script src="https://code.jquery.com/jquery-1.12.4.js"></script><script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script><div class="ui-widget"> <label for="tags">Tags: </label> <input id="tags"></div>

Jquery UI Autocomplete with JSON not working

In your code, the autocomplete function just needs to provide the source parameter with a callback function. source: function( request, response ) {}

You can follow the example for Multiple remote suggestions on jQuery UI Autocomplete

    <script type="text/javascript"> 
$(function() {
function split( val ) {
return val.split( /,\s*/ );
}
function extractLast( term ) {
return split( term ).pop();
}

$( "#search" )
// don't navigate away from the field on tab when selecting an item
.bind( "keydown", function( event ) {
if ( event.keyCode === $.ui.keyCode.TAB &&
$( this ).data( "ui-autocomplete" ).menu.active ) {
event.preventDefault();
}
})
.autocomplete({
source: function( request, response ) {
$.getJSON( "http://192.168.33.10/app_dev.php/search/query/" + extractLast( request.term ), {
term: extractLast( request.term )
}, response );
},
search: function() {
// custom minLength
var term = extractLast( this.value );
if ( term.length < 2 ) {
return false;
}
},
focus: function() {
// prevent value inserted on focus
return false;
},
select: function( event, ui ) {
var terms = split( this.value );
// remove the current input
terms.pop();
// add the selected item
terms.push( ui.item.value );
// add placeholder to get the comma-and-space at the end
terms.push( "" );
this.value = terms.join( ", " );
return false;
}
});
});
</script>

The JSON returned by the server in this example would be structured like this:

[{"id":"1544","label":"Suggestion 1","value":"Suggestion 1"},
{"id":"3321","label":"Suggestion 2","value":"Suggestion 2"}]

jQuery autocomplete with callback ajax json

Perfectly good example in the Autocomplete docs with source code.

jQuery

<script>
$(function() {
function log( message ) {
$( "<div>" ).text( message ).prependTo( "#log" );
$( "#log" ).scrollTop( 0 );
}

$( "#city" ).autocomplete({
source: function( request, response ) {
$.ajax({
url: "http://gd.geobytes.com/AutoCompleteCity",
dataType: "jsonp",
data: {
q: request.term
},
success: function( data ) {
response( data );
}
});
},
minLength: 3,
select: function( event, ui ) {
log( ui.item ?
"Selected: " + ui.item.label :
"Nothing selected, input was " + this.value);
},
open: function() {
$( this ).removeClass( "ui-corner-all" ).addClass( "ui-corner-top" );
},
close: function() {
$( this ).removeClass( "ui-corner-top" ).addClass( "ui-corner-all" );
}
});
});
</script>

HTML

<div class="ui-widget">
<label for="city">Your city: </label>
<input id="city">
Powered by <a href="http://geonames.org">geonames.org</a>
</div>

<div class="ui-widget" style="margin-top:2em; font-family:Arial">
Result:
<div id="log" style="height: 200px; width: 300px; overflow: auto;" class="ui-widget-content"></div>
</div>

AutoComplete jQuery Using JSON data

Using a remote data source:

$("#selector").autocomplete({
source: function (request, response) {
$.ajax({
url: "my_server_side_resource.php",
type: "GET",
data: request,
success: function (data) {
response($.map(data, function (el) {
return {
label: el.color,
value: el.value
};
}));
}
});
},
select: function (event, ui) {
// Prevent value from being put in the input:
this.value = ui.item.label;
// Set the next input's value to the "value" of the item.
$(this).next("input").val(ui.item.value);
event.preventDefault();
}
});

Tweak the $.ajax call as needed. This example will generate requests to your PHP resource that look like this:

my_server_side_resource.php?term=xyz

If you have control over your server-side code, you could change the data that's returned to look like this:

[
{
label: "red",
value: "#f00"
}, /* etc */
]

You can simply use a string, the name of your server-side resource as the source:

$("#selector").autocomplete({
source: "my_server_side_resource.php",
select: /* same as above */
});

Check out the remote with JSONP example for a full example using a server-side resource.

Edit: See this example for a working demo using local data: http://jsfiddle.net/SMxY6/



Related Topics



Leave a reply



Submit