Its not because of the scope. It is because of the asynchronous behaviour of ajax call. Because the function will not wait for the success event of ajax.
If you want to return, you should use async:false
in ajax. But it is not a good method of coding.
Or you should restructure your code with the asynchronous ajax. Instead of returning the value, call a function in the ajax success with desired id.