Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 296
Chris Worrell Avatar asked Jul 11 '12 14:07

Chris Worrell


2 Answers

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" }); 
like image 153
Andrew Whitaker Avatar answered Sep 23 '22 21:09

Andrew Whitaker


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();   } } 
like image 25
Developer Avatar answered Sep 23 '22 21:09

Developer