marschro
marschro

Reputation: 791

jquery.post and variable scope

I'm new to javascript and have the following problem. I want to load some json from an api.php and succeed with the returned value to fill my GUI.

    $( '#data_button' ).click(function() {
    $.post( 'api.php', function( data ) { json = data; });
    $('#data1').empty().append( json[0].name + ' | ' + json[1].name );
});

So I wanna click a button, then it fetches via post some data ans save this to the variable data. As it should be an object (json object?) I thought I just can use it as above... But that doesn't work. Console say: can't find variable json.

Any hints?

Upvotes: 0

Views: 271

Answers (2)

Noampz
Noampz

Reputation: 1205

jquery post as default works asynchronously which means that the line:

$('#data1').empty().append( json[0].name + ' | ' + json[1].name );

occur before the post request have returned the data.

this how it should be done:

$( '#data_button' ).click(function() {
     $.post( 'api.php', function( data ) { 
         $('#data1').empty().append( data[0].name + ' | ' + data[1].name );
     });
});

Upvotes: 2

Malk
Malk

Reputation: 11983

You have your appending outside the post callback function. Try this:

$( '#data_button' ).click(function() {
    $.post( 'api.php', function( data ) { 
        json = data; 
        $('#data1').empty().append( json[0].name + ' | ' + json[1].name );
     });
});

Upvotes: 2

Related Questions