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 “” . 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";
 url: ''+"freecodecamp"+'?callback=?',
 data: { format: 'json'},
 dataType: 'jsonp',
 success: function(x)


$.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 ( 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;

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