0

I was trying to return a value after an ajax call in a function and it kept returning undefined.

I looked it up and learned about callbacks.

I am starting to understand the concept, but little confused over handling it the way I want to

The function:

function count_posts(post_type, callback) {


    var s_data = {
        count_posts: 1,
        post_type: post_type    
    }

    $.post("actions.php", s_data, function(data) {

        var r = JSON.parse(data);

        callback(r);

    });

} // EO count_posts

calling it:

count_posts('all', function(count) { console.log(count); }); // 20 ( working )

handling it differently:

console.log(count_posts('all', function(count) { return count; })); // undefined

Goal:

$('#show_count').html(count_posts('all', function(count) { return count; }))

How do I handle a callback in the way that I want to handle it.

Andy
  • 17
  • 6

2 Answers2

0

The function doesnt return a value. The callback is called async

try calling it like this:

count_posts('all', function(count) { 
   $('#show_count').html(count);
});
Kinnza
  • 1,241
  • 10
  • 13
0

The point with such callbacks is, that they are somewhat "called from nowhere".. so you will not return it a value to your code. Instead reverse the call order, in your example:

count_posts('all', function(count) { $('#show_count').html(count); });
fast
  • 885
  • 7
  • 15