-1

I get nickname, attack_point data using ajax

var nickname;
$.ajax({
            method:'GET',
            url:get_gamestart_api_url,

        }).done(function(data){

            $get_id.append("<li class='nickname'>" character.nickname+"</li>",
                "<li class='attack_point'>" character.status.attack_point+"</li>",
                    );
            nickname=character.nickname;
        });

console.log(nickname);

The script shows me undefined.

I think console.log(nickname); was executed before done(). Why is this happening?

plase somebody help me thank you :)

Neil
  • 14,063
  • 3
  • 30
  • 51
Jade Han
  • 1,185
  • 5
  • 15
  • 36
  • 1
    Make sure you read the entire accepted answer of the suggested duplicate, and **understand** it. If you're going to be using JS, it's **imperative** that you know how to handle async code, and how it differs from synchronous code. – Carcigenicate Mar 16 '17 at 17:14
  • @Andreas, and 'Carcigenicate' thanks for the good advise! from now on, I can understand different between Asynchronous, synchronous! my question is so stupid,, I tried eat bread before get it... thank you – Jade Han Mar 17 '17 at 04:13

1 Answers1

0

The console.log(nickname); was executed before .done() because Ajax request are asynchronous, which means they are procesed in the background. That means that the program isn't necesarily executed in the order you wrote it. If you want console.log(nickname); to be executed once the Ajax request is done, you should include it in the .done() function

Larpee
  • 800
  • 1
  • 7
  • 18
  • thank you @Larpee but this advise not a solution for me, becuase I want use nickname value outside – Jade Han Mar 17 '17 at 02:46
  • 1
    @Min What exactly do you want to do? Maybe I can help you with that – Larpee Mar 17 '17 at 14:14
  • Thank you @Larpee, here is my [link](https://gist.github.com/deadlylaid/5cc840a9ceccfbadead5f2c835591153) what i want, but I solved my problem already using `callback()` but Thank you for your kindness. Larpee – Jade Han Mar 17 '17 at 14:24
  • 1
    @Min Okay, I'm glad you solved your problem – Larpee Mar 17 '17 at 20:20