Global variable is not working in jquery funtion

To complete freecodecamp’s “twitchTv” project, I write some code. I found that below type of code gives output ‘rana’ and “https://static-cdn.jtvnw.net/jtv_user_pictures/freecodecamp-profile_image-d9514f2df0962329-300x300.png” . I think it should give url first.If I comment out first window.alert (inside the function) then gives output only ‘rana’ . I think this variable should give the url of the logo. I do not know why this happens and how to solve the problem.

var logo="rana";
   
  $.ajax({
 url: 'https://wind-bow.gomix.me/twitch-api/users/'+"freecodecamp"+'?callback=?',
 data: { format: 'json'},
 dataType: 'jsonp',
 success: function(x)
 {
    logo=x.logo;
    window.alert(logo);
 }
 });

 window.alert(logo);

$.ajax() is asynchronous, so the code below it (window.alert(logo)) is run before the variable has changed.

Because the .ajax function is asynchronous, JavaScript will continue executing code after this AJAX call (your outer alert in your code) until a successful response comes back from the API ( https://wind-bow.gomix.me/twitch-api). When a successful response finally comes back, then the anonymous function of the success property executes (the inner alert you have).

I want that the varible should have the url value ,such that I can use it further.Is it possible?

You can use it inside the success callback function.

In success callback function the variable gets the value , but when I want to use it later (outside the function) , the variable gives me previous value ‘Rana’ ;

Yes, that is because the request is not finished.

You can use it inside the callback and pass it to another function:

...
success: function(x){
  logo = x.logo;
  doSomethingWithNewLogoValue(logo);
}
...

// outside $.ajax:
function doSomethingWithNewLogoValue(logo){
  alert(logo);
}
1 Like