Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

177
Views
What does autocomplete request/server response look like?

This seems to be a black hole: After an hour of searching the jQuery UI website, Stack Overflow, and googling, I've yet to find the most basic information of how to write the server side of the AutoComplete.

What parameter is passed to the server and what should the JSON response look like?

I must be missing something, because how did everyone else learn how to do this? Sites only seem to discuss the client-side JavaScript code and never the protocol or server-side examples.

I need enough to get the simplest remote example working.

over 4 years ago · Santiago Trujillo
3 answers
Answer question

0

What parameter is passed to the server

You need to pass request.term to your server-side code (from the documentation):

A request object, with a single property called "term", which refers to the value currently in the text input.

Basically, in your autocomplete code, you'll have something like this:

$("#autocomplete").autocomplete({
    // request.term needs to be passed up to the server.
    source: function(request, response) { ... }
});

and what should the JSON response look like?

The autocomplete widget expects an array of JSON objects with label and value properties (although if you just specify value, it will be used as the label). So in the simplest case, you can just return data that looks like this:

[
    { label: 'C++', value: 'C++' }, 
    { label: 'Java', value: 'Java' }
    { label: 'COBOL', value: 'COBOL' }
]

If you need something more complicated, you can use the success argument of the $.ajax function to normalize the data you get back before the autocomplete gets it:

source: function( request, response ) {
    $.ajax({
        /* Snip */
        success: function(data) {
            response($.map( data.geonames, function( item ) {
                return {
                    label: item.name + (item.adminName1 ? ", " + item.adminName1 : "") + ", " + item.countryName,
                    value: item.name
                }
            }));
         }
    });

This code is taken from the example here (This is a good example overall of ajax + autocomplete works in a more complex scenario).

Basically, what's going is that upon a successful ajax request, the data received is being normalized (using $.map) to what the autocomplete widget expects.

Hope that helps.

over 4 years ago · Santiago Trujillo Report

0

In addition to Andrew Whitaker's perfect answer, an alternative method to $.map is to override the renderer, an example of which is shown on the jQuery UI Demo page.

I have used this functionality using a JSON call like so:

JSON Response

{
   "Records": [
       {
           "WI_ID": "1",
           "Project": "ExampleProject",
           "Work_Item": "ExampleWorkItem",
           "Purchase_Order": "",
           "Price": "",
           "Comments": "",
           "Quoted_Hours": "",
           "Estimated_Hours": "",
           "Achieved": "False",
           "Used_Hours": "0"
       }
   ]
}

jQuery

$("#WorkItem").autocomplete({
      source: function(request, response){
           $.ajax({
               type: "POST",
               url: "ASPWebServiceURL.asmx/WorkItems",
               data: "{'Project_ID':'1'}",
               contentType: "application/json; charset=utf-8",
               dataType: "json",
               success: function (msg) {
                   response($.parseJSON(msg.d).Records);
               },
               error: function (msg) {
                   alert(msg.status + ' ' + msg.statusText);
               }
           })
       },

       select: function (event, ui) {
           $("#WorkItem").val(ui.item.Work_Item);
           return false;
       }
})
.data("autocomplete")._renderItem = function (ul, item) {
    return $("<li></li>")
    .data("item.autocomplete", item)
    .append("<a>" + item.Work_Item + "</a>")
    .appendTo(ul);
};

In this example, the _renderItem function is overridden so that the search result list (i.e, the list that appears under the textbox) is filled using attributes of the records that I retrieved from the JSON response.

Whilst not as simple, it allows you to pull off some pretty interesting stuff (using multiple bits of data from a JSON response, for example)

over 4 years ago · Santiago Trujillo Report

0

Both answers so far are complex and misleading, a key understanding to jQuery UI Auto Complete is the success anonymous function, you have leverage/control of the format of your server side JSON response because of the success callback of AutoComplete. The label,value format is a good one to follow but you can define any JSON format you desire, the key is how you define your success function:

 <input id="refPaymentTerms" class="form-control">

$("#refPaymentTerms").autocomplete({
                source: function (request, response) {
                    $.ajax({
                        type: "POST",
                        url: "/admin/JobPaymentRefs",
                        dataType: "json",
                        data: {
                            term: request.termCode
                        },
                        error: function (xhr, textStatus, errorThrown) {
                            alert('Error: ' + xhr.responseText);
                        },
                        success: function (data) {
                            response($.map(data, function (item) {
                                return {
                                    label: item.label,
                                    value: item.value
                                }
                            }));
                        }
                    });
                }
            });

MVC Controller:

public JsonResult JobPaymentRefs()
    {
        var query = from REFTerm in _db.REFTerms
                     select new
                    {
                        label = REFTerm.TermCode,
                        value = REFTerm.TermCode
                    };
        //var refTerms = _db.REFTerms.Select(x => x.TermCode);

        return Json(query.ToArray());
    }

Here we see a very standard auto complete bind with an ASP.NET backend.

You can return whatever format of JSON you desire server side as long as you map it correctly in the AutoComplete anonymous callback. The label,value name value pair is good enough for most requirements but do as you will server side with your JSON just map it correctly in the AutoComplete success callback.

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!