views:

132

answers:

2

Hi Everyone, Only started today but I'm having massive problems trying to understand JSON/AJAX etc, I've gotten my code this far but am stumped on how to return the data being pulled by the AJAX request to the jQuery Auto complete function.

var autocomplete = new function (){
this.init = function() {
    $('#insurance_destination').autocomplete({source: lookup});  
}

  function lookup(){
     $.ajax({  
        url: "scripts/php/autocomplete.php",
        data: {query:this.term},
        dataType: "json",
        cache : false, 
        success: function(data) {    
            for(key in data){
              return {
                     label: key,
                     value: data[key][0]
                     }
            }                                    
        }      
});
}

}

And example of the JSON string being returned by a PHP script {"Uganda":["UGA","UK4","Worldwide excluding USA, Canada and the Carribbean"]}

+1  A: 

Normally, you don't have to do ajax query yourself:

$('#insurance_destination').autocomplete('url_here', {options_here});

That's assuming we're talking about standard jquery autocomplete plugin. Do I understand you correctly?

edit Check api
http://docs.jquery.com/Plugins/Autocomplete/autocomplete#url_or_dataoptions
There are also some examples.

Nikita Rybak
I did try that too, but it doesn't seem to work either... that might be a problem with my PHP, although with the manual code it does return a JSON string that seems to work fine, but I just can't get the autocomplete box to populate with the data.
RohanCS
It's not supposed to take json, values should be separated by line breaks. Check this page with examples, and in particular sample php script provided: http://view.jquery.com/trunk/plugins/autocomplete/demo/Let me know if it helps.
Nikita Rybak
A: 

This is the code I've ended up with, it works in Chrome and Firefox but not in IE 6/7...

var autocomplete = new function (){
    this.init = function() { 
        $('#insurance_destination').autocomplete({ 
            source: function(request, response) {
                debugger;
                $.ajax({
                    url: "scripts/php/autocomplete.php",
                    dataType: "json",
                    data: {query:this.term},  
                    success: function(data) {
                    response($.map(data.countries, function(item) {
                        return {
                            label: '<strong>'+item.name+'</strong>'+' '+item.description,
                            value: item.name,
                            code : item.region
                        }
                    }))
                }
            })
        },
        minLength: 2,
        select: function(event, ui) {
            $('#insurance_iso_code_hidden').val(ui.item.code);
        },
        open: function() {
        },
        close: function() {

        }
        });  
    } 


    }
RohanC.S