[jquery] jQuery autocomplete with callback ajax json

I'm trying to find a way to use jQuery autocomplete with callback source getting data via an ajax json object list from the server.

Could anybody give some directions?

I googled it but couldn't find a complete solution.

This question is related to jquery json autocomplete

The answer is


I hope this helps:

var token = document.getElementById('token').value;
var nombre = document.getElementById('txtNombre').value;    

$("#txtNombre").keyup(function () {
    $.ajax({
        type: "POST",
        url: host() + "Formulario/BuscarNombreAutocompletar/",
        data: JSON.stringify({ "nombre": nombre }),
        headers: {
            'Authorization': 'Bearer ' + token
        },
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (data) {
            var dataArray = [];
            if (controlCarga(data)) {

                $.each(data[1], function (i, item) {
                    dataArray.push(item.frmNombre)
                });

                $('#txtNombre').autocomplete({
                    clearButton: true,
                    source: dataArray,
                    selectFirst: true,
                    minLength: 2
                });
            }
        },
        error: function (xhr, textStatus, errorThrown) {
            console.log('Error: ' + xhr.responseText);
        }
    });
});

I used the construction of $.each (data [i], function (key, value) But you must pre-match the names of the selection fields with the names of the form elements. Then, in the loop after "success", autocomplete elements from the "data" array. Did this: autocomplete form with ajax success


If you are returning a complex json object you need to modify you success function of your auto-complete as follows.

$.ajax({
    url: "/Employees/SearchEmployees",
    dataType: "json",
    data: {
        searchText: request.term
    },
    success: function (data) {
        response($.map(data.employees, function (item) {
            return {
                label: item.name,
                value: item.id
            };
        }));
    }
});

My issue was that end users would start typing in a textbox and receive autocomplete (ACP) suggestions and update the calling control if a suggestion was selected as the ACP is designed by default. However, I also needed to update multiple other controls (textboxes, DropDowns, etc...) with data specific to the end user's selection. I have been trying to figure out an elegant solution to the issue and I feel the one I developed is worth sharing and hopefully will save you at least some time.

WebMethod (SampleWM.aspx):

  • PURPOSE:

    • To capture SQL Server Stored Procedure results and return them as a JSON String to the AJAX Caller
  • NOTES:

    • Data.GetDataTableFromSP() - Is a custom function that returns a DataTable from the results of a Stored Procedure
    • < System.Web.Services.WebMethod(EnableSession:=True) > _
    • Public Shared Function GetAutoCompleteData(ByVal QueryFilterAs String) As String

 //Call to custom function to return SP results as a DataTable
 // DataTable will consist of Field0 - Field5
 Dim params As ArrayList = New ArrayList
 params.Add("@QueryFilter|" & QueryFilter)
 Dim dt As DataTable = Data.GetDataTableFromSP("AutoComplete", params, [ConnStr])

 //Create a StringBuilder Obj to hold the JSON 
 //IE: [{"Field0":"0","Field1":"Test","Field2":"Jason","Field3":"Smith","Field4":"32","Field5":"888-555-1212"},{"Field0":"1","Field1":"Test2","Field2":"Jane","Field3":"Doe","Field4":"25","Field5":"888-555-1414"}]
 Dim jStr As StringBuilder = New StringBuilder

 //Loop the DataTable and convert row into JSON String
 If dt.Rows.Count > 0 Then
      jStr.Append("[")
      Dim RowCnt As Integer = 1
      For Each r As DataRow In dt.Rows
           jStr.Append("{")
           Dim ColCnt As Integer = 0
           For Each c As DataColumn In dt.Columns
               If ColCnt = 0 Then
                   jStr.Append("""" & c.ColumnName & """:""" & r(c.ColumnName) & """")
               Else
                   jStr.Append(",""" & c.ColumnName & """:""" & r(c.ColumnName) & """")
                End If
                ColCnt += 1
            Next

            If Not RowCnt = dt.Rows.Count Then
                jStr.Append("},")
            Else
                jStr.Append("}")
            End If

            RowCnt += 1
        Next

        jStr.Append("]")
    End If

    //Return JSON to WebMethod Caller
    Return jStr.ToString

AutoComplete jQuery (AutoComplete.aspx):

  • PURPOSE:
    • Perform the Ajax Request to the WebMethod and then handle the response

    $(function() {
      $("#LookUp").autocomplete({                
            source: function (request, response) {
                $.ajax({
                    type: "POST",
                    contentType: "application/json; charset=utf-8",
                    url: "SampleWM.aspx/GetAutoCompleteData",
                    dataType: "json",
                    data:'{QueryFilter: "' + request.term  + '"}',
                    success: function (data) {
                        response($.map($.parseJSON(data.d), function (item) {                                
                            var AC = new Object();

                            //autocomplete default values REQUIRED
                            AC.label = item.Field0;
                            AC.value = item.Field1;

                            //extend values
                            AC.FirstName = item.Field2;
                            AC.LastName = item.Field3;
                            AC.Age = item.Field4;
                            AC.Phone = item.Field5;

                            return AC
                        }));       
                    }                                             
                });
            },
            minLength: 3,
            select: function (event, ui) {                    
                $("#txtFirstName").val(ui.item.FirstName);
                $("#txtLastName").val(ui.item.LastName);
                $("#ddlAge").val(ui.item.Age);
                $("#txtPhone").val(ui.item.Phone);
             }                    
        });
     });


$(document).on('keyup','#search_product',function(){
    $( "#search_product" ).autocomplete({
      source:function(request,response){
                  $.post("<?= base_url('ecommerce/autocomplete') ?>",{'name':$( "#search_product" ).val()}).done(function(data, status){

                    response(JSON.parse(data));
        });
      }
    });
});

PHP code :

public function autocomplete(){
    $name=$_POST['name'];
    $result=$this->db->select('product_name,sku_code')->like('product_name',$name)->get('product_list')->result_array();
    $names=array();
    foreach($result as $row){
        $names[]=$row['product_name'];
    }
    echo json_encode($names);
}

Examples related to jquery

How to make a variable accessible outside a function? Jquery assiging class to th in a table Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Getting all files in directory with ajax Bootstrap 4 multiselect dropdown Cross-Origin Read Blocking (CORB) bootstrap 4 file input doesn't show the file name Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource how to remove json object key and value.?

Examples related to json

Use NSInteger as array index Uncaught SyntaxError: Unexpected end of JSON input at JSON.parse (<anonymous>) HTTP POST with Json on Body - Flutter/Dart Importing json file in TypeScript json.decoder.JSONDecodeError: Extra data: line 2 column 1 (char 190) Angular 5 Service to read local .json file How to import JSON File into a TypeScript file? Use Async/Await with Axios in React.js Uncaught SyntaxError: Unexpected token u in JSON at position 0 how to remove json object key and value.?

Examples related to autocomplete

twitter bootstrap 3.0 typeahead ajax example How do I stop Notepad++ from showing autocomplete for all words in the file how to get value of selected item in autocomplete .autocomplete is not a function Error Angularjs autocomplete from $http autocomplete ='off' is not working when the input type is password and make the input field above it to enable autocomplete Disabling Chrome Autofill How to add Google Maps Autocomplete search box? Google Maps API - how to get latitude and longitude from Autocomplete without showing the map? twitter bootstrap autocomplete dropdown / combobox with Knockoutjs