0

I'm working on function which provides data to other jQuery callbacks. The problem is I haven't got it to work jet. When I just put the content of the fetchdata() function right into the .click callback, it works, but I need a separate generic function so I can use it with multiple different callbacks in the future. Can anyone point me out what I'm doing wrong here? It seems the loop within the fetchdata() function breaks and no value is returned.

    function fetchdata(){
        var html;
        $.ajax({
            url:'/test.php', 
            data:{ action: 'fetch-data' },
            dataType:'json',
            async: false,
            success: function(data){
                var entries = [];
                $.each(data, function(id, val){
                    entries.push(val.sample);
                });
                var html = entries.join('');
            }
        });
        return html;
    }
    $(document).on('click', 'a.btn.execute', function(e) {
        e.preventDefault();
        var html =  fetchdata();
        $('div#container').html(html);
    });

PS: I altered my code a bit for the demo above, the problem should still be there.

carlo
  • 700
  • 2
  • 9
  • 25

1 Answers1

2

It happens because you've got var html = entries.join(''); inside the success callback which is overlapping your previous html variable. Just html = entries.join(''); would work. But please don't really use async: false since it's obsolete

Here's a better solution:

function fetchdata(callback){
    $.ajax({
        url:'/test.php', 
        data:{ action: 'fetch-data' },
        dataType:'json',
        success: function(data){
            var entries = [];
            $.each(data, function(id, val){
                entries.push(val.sample);
            });
            var html = entries.join('');
            callback(html);
        }
    });
}
$(document).on('click', 'a.btn.execute', function(e) {
    e.preventDefault();
    fetchdata(function(html){
      $('div#container').html(html);
    });
});
Kirill Ivlev
  • 12,310
  • 5
  • 27
  • 31
  • Thank you, your solution works fine for me! Just one more question; what should I do in order to pass extra parameters to the function? – carlo Nov 11 '12 at 21:42
  • Nevermind, got it. (fetchdata('parameter', function(html){ ...) – carlo Nov 11 '12 at 21:46