0

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?

Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
marschro
  • 791
  • 8
  • 23
  • This doesn't have anything to do with scope, only with timing. Please have a look at [How to return the response from an AJAX call?](http://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-ajax-call) – Felix Kling Nov 29 '13 at 22:10
  • 1
    I'd suggest you to read about asynchronous programming and JavaScript's function scope. – Adonis K. Kakoulidis Nov 29 '13 at 23:10

2 Answers2

2

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 );
     });
});
Malk
  • 11,855
  • 4
  • 33
  • 32
2

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 );
     });
});
Noampz
  • 1,185
  • 3
  • 11
  • 19