Matarishvan
Matarishvan

Reputation: 2422

jQuery autocomplete with AJAX JSON

I'm trying to have dynamic autocomplete values for a textbox.

This is my response:

echo json_encode($res)

0: {type_name: "name1"}
1: {type_name: "name2"}
2: {type_name: "name3"}
3: {type_name: "name4"}
4: {type_name: "name5"}

And this is my autocomple ajax code:

 $( "#txt_box" ).autocomplete({
  source: function( request, response ) {
      $.ajax({
        type:"POST",
        url: "index.php?action=autocomplete",                   
        dataType: "json",
        data: {
            q: request.term
        },
        success: function( data ) {
            response( data );
        }
    });
  }
 });    

I'm not able to figure out if there is any issue in my JSON format or in my AJAX code. I'm not able to get the autocomplete dropdown based on the keysearch.

Upvotes: 0

Views: 119

Answers (2)

Gopal Satpati
Gopal Satpati

Reputation: 136

Don't call ajax request into the autocomplete function. As per your requirement, first you need to collect data json format:

var jsonData = ["name1","name2","name3",.......];
$( "#txt_box" ).autocomplete({ source:jsonData });   

Please follow the link: https://jqueryui.com/autocomplete/

Upvotes: 1

Jozef Chocholacek
Jozef Chocholacek

Reputation: 2924

As described in http://api.jqueryui.com/autocomplete/#option-source, the data object passed to the response callback can be either an array of strings or array of objects with label and value properties. Your response does not seem to be any of these.

So either you have to fix your response, to provide e.g. [ "name1", "name2", "name3", "name4", "name5" ] (i.e. array of strings), or you must process this response in your success callback, to forward the data to the response callback in a correct format.

Upvotes: 1

Related Questions