1

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);
    }
});
Priya
  • 11
  • 1
  • 5
  • you can't do that... returning a value from an async method like an ajax call... see http://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-ajax-call – Arun P Johny Feb 16 '14 at 10:05
  • slightly offtopic, but http://rog.ie/blog/dugjs-a-jsonp-to-html-script is a very clean solution to populating html with json data – roman Feb 16 '14 at 10:40

2 Answers2

1

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);
            }
        });
    })
});
Community
  • 1
  • 1
Arun P Johny
  • 384,651
  • 66
  • 527
  • 531
0

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) {
zzlalani
  • 22,960
  • 16
  • 44
  • 73