Jquery UI autocomplete with Ajax: the novice stage

stage 2: novice
we will try to understand that thing a bit with our own server side.
add new item, choose Generic Handle, th filename will be Handler1.ashx.
paste this:
public void ProcessRequest(HttpContext context)
{
 
context.Response.ContentType = "text/plain";
  JavaScriptSerializer jss = new JavaScriptSerializer();
  var x = new string[] { "ariel", "avraham", "aviel", "eliyahu", "eliezer" };
  context.Response.Write(jss.Serialize(x));
}

client side paste this
$(function () {
  $("#MyTextBox").autocomplete({ source: "Handler1.ashx" });
});

yep, the autocomplete source can get a pure handler. try it and see that we now have our own handler, now lets make it ajax with server side filter, start with asking for the same data but with the filter function
$("#MyTextBox").autocomplete({
  source: function (request, response) {
    $.ajax({
     
url: "Handler1.ashx",
      success: function (data) {
        response($.map(data, function (item) {
          return { label: item }
        }))
      }
   })
  }
});
 


so how do we filter that? the request object have a thing call request.term, thats what the user put in the textbox, so we want to send it to our handler, so with using data{} on the ajax call we just send parameters to the QueryString on the server side so:

context.Response.ContentType = "application/json";
JavaScriptSerializer jss = new JavaScriptSerializer();
var filter = context.Request.QueryString["Filter"];
var x = new string[] { "ariel", "avraham", "aviel", "eliyahu", "eliezer" };
var response = jss.Serialize(x.Where(s => s.Contains(filter)));
context.Response.Write(response);

and client side

$.ajax({
 
url: "Handler1.ashx",
  data: "Filter=" + request.term,
  success: function (data) {
    response($.map(data, function (item) {
      return { label: item }
    }))
  }
})
 


and BANG it does the magic! so here we learned how to make both server-side and cliend side simple autocomplete with ajax requests.

next some nice things we can do with all that except autocomplete
http://bresleveloper.blogspot.co.il/2013/04/jquery-ui-autocomplete-with-ajax_5.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