0

i have this simple code snippet for store token in global way but i dont understand why when i alert token varibale it shows me undefined . im new comer in js but it is very simple im confused !

$(document).ready(function() {
    let token;
    $("#login-form").submit(function (e) {
        e.preventDefault();
        let username = $("#username").val();
        let password = $("#password").val();
        $.ajax({
            type:'post',
            url:'http://localhost:8000/api/login',
            data:{
                'username': username,
                'password': password,
            },
            success:(function (response) {
                if(!localStorage.getItem('token'))
                    localStorage.setItem('token',response.token)
                    token = localStorage.getItem('token');
                })
            });
            alert(token);
        })
    });
executable
  • 3,365
  • 6
  • 24
  • 52
sinak
  • 222
  • 6
  • 19
  • You're alerting the token immediately after the asynchronous ajax request – Callam Oct 12 '18 at 14:05
  • 2
    It's not relevant, but: `token` isn't a global. (Which is good.) See the linked question's answers for relevant information, tnough. :-) – T.J. Crowder Oct 12 '18 at 14:05
  • @Callam so whats the problem ! i want to check it after ajax for test in this example i alert it . could you tell me what is the correct form? – sinak Oct 12 '18 at 14:10
  • @sinak The problem is your alerting the result for something that has not yet happened,.. Place your alert inside the `success` handler, and it should work. For more detailed answer, please follow the link TJ supplied. – Keith Oct 12 '18 at 14:17

0 Answers0