Jquery UI autocomplete with Ajax: the idiotproof to master full guide

i decided to write this post cuz this thing tool my like an hour or 2 to get, and while looking at my solution i saw i should have got it in 2 seconds, so like other places sometime the examles are just not simple enough, so lets go.

stage 1: idiot proof
i'll do everything from the begining, download jquery ui 1.9.2 from their site. i opened an empty asp.net web app, added the jquery-ui-1.9.2.custom.js and the jquery-1.8.3.js and write html:

<input id="MyTextBox" type="text" />
and then JS:
$(function () {
  $("#MyTextBox").autocomplete({
    source: [ "ariel", "avraham", "aviel", "eliyahu", "eliezer" ]
  });
});
 


and run, thas it u have a working auto complete. now in order to have my array from a request i could just do this:
$.ajax({
 
url: "default.aspx/BringMeListFromWebMethod",
  contentType: "application/json; charset=utf-8",
  type: "POST",
  async: false,
  success: function (data) { arr = data.d; }
});
$("#MyTextBox").autocomplete({  source: arr }); 

of course the BringMeListFromWebMethod is a WebMethod that return the same string[].
for any1 who need some instructions about basics of ajax or WebMehtods:
http://bresleveloper.blogspot.co.il/2012/04/ajax-3-simle-ways.html

but then we want to already do the filtering server side, otherwise whats the point? so in order to make it simple we will use what Jquery UI gives us for free,
$("#MyTextBox").autocomplete({
  source: function (request, response) {
    $.ajax({
     
url: http://ws.geonames.org/searchJSON,
      dataType: "jsonp",
      data: { name_startsWith: request.term },
     
success: function (data) {
        response($.map(data.geonames, function (item) {
          return { label: item.name }
        }))
      }
    })
  }
});
 


i'll put it up to you to call the right ajax thing for you app and make sure its json, its a problem to use webmethod, easier to make a handler or something and u need to json serialize it.

but still a little overview: the url is a ajax handler that returns a large array in json.
the data sends the request.term, that what you put in the textbox, to the right parameter.
lastly the label:item.name, that creates the list you will see.

join us again in the novice stage here
http://bresleveloper.blogspot.co.il/2013/04/jquery-ui-autocomplete-with-ajax-novice.html

Comments

Popular posts from this blog

c# Service Play Sound with NAudio example by Moshe

SOLVED The item could not be indexed successfully because the item failed in the indexing subsystem

JS/JQ simulate Enter event