Priya
Priya

Reputation: 11

JSON for popuplate HTML div

I am trying to use an JSON string to popolate an html div, here's my code, but it seems not working, I still cannot realize why, there's some suggestions?

The JSON is created via PHP and it is working fine. Thank you.

    $(document).ready(function(e) {
    var Currencies = function(){
        $.ajax({
            url:"js/php/users.php",
            success:function(data){
                return{
                    getMyJson: function(data){
                        return(data);
                    }
                }
            }
        });     
    }(); // execute the function when the MyObj variable is initialized.   
});
$('#autocomplete').autocomplete({
    lookup: Currencies.getMyJson(),
    onSelect: function (suggestion){
        var thehtml = '<strong>Currency Name:</strong> ' + suggestion.nome + ' <br> ';
        $('#outputcontent').html(thehtml);
    }
});

Upvotes: 1

Views: 81

Answers (2)

Arun P Johny
Arun P Johny

Reputation: 388406

Few observations

  • The Currencies object is local to the dom ready handler, so it is not accessible outside it. Move your autocomplete plugin initialization inside the dom ready handler.
  • You can't return a value from a asynchronous method like that - See How to return the response from an AJAX call

Try

$(document).ready(function (e) {
    var Currencies = {
        getMyJson: function (callback) {
            $.ajax({
                url: "js/php/users.php",
                success: function (data) {
                    callback(data)
                }
            });
        }
    }; // execute the function when the MyObj variable is initialized.   

    Currencies.getMyJson(function (data) {
        $('#autocomplete').autocomplete({
            lookup: data,
            onSelect: function (suggestion) {
                var thehtml = '<strong>Currency Name:</strong> ' + suggestion.nome + ' <br> ';
                $('#outputcontent').html(thehtml);
            }
        });
    })
});

Upvotes: 1

zzlalani
zzlalani

Reputation: 24384

move this code

$('#autocomplete').autocomplete({
    lookup: Currencies.getMyJson(),
    onSelect: function (suggestion){
        var thehtml = '<strong>Currency Name:</strong> ' + suggestion.nome + ' <br> ';
        $('#outputcontent').html(thehtml);
    }
});

into

$(document).ready(function(e) {

Upvotes: 0

Related Questions