[jquery] jQuery UI autocomplete with JSON

Alright been racking my brain on this (im terrible at this) but yea ive tried reading all i can and still cant get it to work.

trying to do autocomplete with jquery ui

my json looks like this

{"dealers":
     {
         "1156":"dealer 1",
         "1122":"dealer 2",
         "1176":"dealer 3",
         "1491":"dealer 4",
         "1463":"dealer 5",
         "269":"dealer 6"
    }
}

i am trying to use this information as the source for autocomplete. i am getting the response object just fine I am just having trouble getting it in the right format so that I can place the "###" in a hidden field tied to the "value" which needs to be displayed as the portion of the drop down.

been trying a million different ways but a recent attempt was below

function ajaxCall() {
    $.getJSON("/example/location/example.json?term=" + $('#dealerName').val(),
        function(data) {
        $.each(data.dealers, function(k, v) {                
                alert(k + ' : ' + v);
        });
    });        
}

$('#dealerName').autocomplete({
    source: ajaxCall,
    minLength: 2,
    delay: 100
});

Please and thank you much!

The answer is


You need to transform the object you are getting back into an array in the format that jQueryUI expects.

You can use $.map to transform the dealers object into that array.

$('#dealerName').autocomplete({
    source: function (request, response) {
        $.getJSON("/example/location/example.json?term=" + request.term, function (data) {
            response($.map(data.dealers, function (value, key) {
                return {
                    label: value,
                    value: key
                };
            }));
        });
    },
    minLength: 2,
    delay: 100
});

Note that when you select an item, the "key" will be placed in the text box. You can change this by tweaking the label and value properties that $.map's callback function return.

Alternatively, if you have access to the server-side code that is generating the JSON, you could change the way the data is returned. As long as the data:

  • Is an array of objects that have a label property, a value property, or both, or
  • Is a simple array of strings

In other words, if you can format the data like this:

[{ value: "1463", label: "dealer 5"}, { value: "269", label: "dealer 6" }]

or this:

["dealer 5", "dealer 6"]

Then your JavaScript becomes much simpler:

$('#dealerName').autocomplete({
    source: "/example/location/example.json"
});

I use this script for autocomplete...

$('#custmoers_name').autocomplete({
    source: function (request, response) {

        // $.getJSON("<?php echo base_url('index.php/Json_cr_operation/autosearch_custmoers');?>", function (data) {
          $.getJSON("Json_cr_operation/autosearch_custmoers?term=" + request.term, function (data) {
          console.log(data);
            response($.map(data, function (value, key) {
                console.log(value);
                return {
                    label: value.label,
                    value: value.value
                };
            }));
        });
    },
    minLength: 1,
    delay: 100
});

My json return :- [{"label":"Mahesh Arun Wani","value":"1"}] after search m

but it display in dropdown [object object]...


I understand that its been answered already. but I hope this will help someone in future and saves so much time and pain.

complete code is below: This one I did for a textbox to make it Autocomplete in CiviCRM. Hope it helps someone

CRM.$( 'input[id^=custom_78]' ).autocomplete({
            autoFill: true,
            select: function (event, ui) {
                    var label = ui.item.label;
                    var value = ui.item.value;
                    // Update subject field to add book year and book product
                    var book_year_value = CRM.$('select[id^=custom_77]  option:selected').text().replace('Book Year ','');
                    //book_year_value.replace('Book Year ','');
                    var subject_value = book_year_value + '/' + ui.item.label;
                    CRM.$('#subject').val(subject_value);
                    CRM.$( 'input[name=product_select_id]' ).val(ui.item.value);
                    CRM.$('input[id^=custom_78]').val(ui.item.label);
                    return false;
            },
            source: function(request, response) {
                CRM.$.ajax({
                    url: productUrl,
                        data: {
                                        'subCategory' : cj('select[id^=custom_77]').val(),
                                        's': request.term,
                                    },
                    beforeSend: function( xhr ) {
                        xhr.overrideMimeType( "text/plain; charset=x-user-defined" );
                    },

                    success: function(result){
                                result = jQuery.parseJSON( result);
                                //console.log(result);
                                response(CRM.$.map(result, function (val,key) {
                                                         //console.log(key);
                                                         //console.log(val);
                                                         return {
                                                                 label: val,
                                                                 value: key
                                                         };
                                                 }));
                    }
                })
                .done(function( data ) {
                    if ( console && console.log ) {
                     // console.log( "Sample of dataas:", data.slice( 0, 100 ) );
                    }
                });
            }
  });

PHP code on how I'm returning data to this jquery ajax call in autocomplete:

/**
 * This class contains all product related functions that are called using AJAX (jQuery)
 */
class CRM_Civicrmactivitiesproductlink_Page_AJAX {
  static function getProductList() {
        $name   = CRM_Utils_Array::value( 's', $_GET );
    $name   = CRM_Utils_Type::escape( $name, 'String' );
    $limit  = '10';

        $strSearch = "description LIKE '%$name%'";

        $subCategory   = CRM_Utils_Array::value( 'subCategory', $_GET );
    $subCategory   = CRM_Utils_Type::escape( $subCategory, 'String' );

        if (!empty($subCategory))
        {
                $strSearch .= " AND sub_category = ".$subCategory;
        }

        $query = "SELECT id , description as data FROM abc_books WHERE $strSearch";
        $resultArray = array();
        $dao = CRM_Core_DAO::executeQuery( $query );
        while ( $dao->fetch( ) ) {
            $resultArray[$dao->id] = $dao->data;//creating the array to send id as key and data as value
        }
        echo json_encode($resultArray);
    CRM_Utils_System::civiExit();
  }
}

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 jquery-ui

How to auto adjust the div size for all mobile / tablet display formats? jQuery not working with IE 11 JavaScript Uncaught ReferenceError: jQuery is not defined; Uncaught ReferenceError: $ is not defined Best Practice to Organize Javascript Library & CSS Folder Structure Change table header color using bootstrap How to get HTML 5 input type="date" working in Firefox and/or IE 10 Form Submit jQuery does not work Disable future dates after today in Jquery Ui Datepicker How to Set Active Tab in jQuery Ui How to use source: function()... and AJAX in JQuery UI autocomplete

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

Examples related to jquery-ui-autocomplete

How to use source: function()... and AJAX in JQuery UI autocomplete How to get jQuery dropdown value onchange event Styling JQuery UI Autocomplete jQuery UI autocomplete with JSON twitter bootstrap typeahead ajax example Limit results in jQuery UI Autocomplete jQuery UI autocomplete with item and id