April 15, 2012

jQuery autocomplete not working for the first attempt

Question by Bashanta Dahal

I have tried to implement dynamic autocomplete in my program. It is working perfectly after first input. But it doesn’t show suggestions for the first attempt. However, server is responding the required source for autocomplete. Here is my code.

       $('.autocomplete').live('keyup', function(){
        $this = $(this);
        var search = $this.val();
        $.ajax({
            url:'/package/index/search/keyword/'+search+'/format/json',
            async: false,
            success: function(res){
                //console.log(res.options);
                //console.log(res.defined_ids);
                staticObject = res.defined_ids;
                $this.autocomplete({
                    source: res.options
                });
            }
        });            
    });

Server side Code is

    $keyword = $this->_getParam('keyword');
    $elementDetailModel = new Package_Model_ElementDetail();
    $arr = $elementDetailModel->searchElementDetail($keyword);
    $this->view->options = $arr['options']; // returns in the format array("test2","my new test", "night stay in delux room")
    $this->view->defined_ids = $arr['defined_ids']; // returns in the format array(21::21=>"test2", 22::22=>"my new test", 24::24=>"night stay in delux room")

when I console logged defined_ids and options in firebug, I got following response when I typed ‘t’ in the text field.
options:

[“test2”, “my new test”, “night stay in delux room”]

defined_ids:

Object { 21::21=”test2″, 22::22=”my new test”, 24::24=”night stay in delux room”}

Any help would be appreciable. Thanks in advance.

Answer by Starx

The format displayed from the firebug, is not that of a JSON. It is an array, which are accessed using indices.

When you are displaying the output, make sure you json_encode() the array first, then display it.

For example, with respect to the question, you final array should look something like this

$array['options'] = array("test2", "my new test", "night stay in room");
//Then you should echo the encoded the array to json

echo json_encode($array);

Next, make sure you views are turned off this request.

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!