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?

2
  • 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? Commented Nov 29, 2013 at 22:10
  • 1
    I'd suggest you to read about asynchronous programming and JavaScript's function scope. Commented Nov 29, 2013 at 23:10

2 Answers 2

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 );
     });
});
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks to all of you! It was just too late... and too obvious.
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 );
     });
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.