I have created an ajax call and i am saving ajax success data in an array, I a calling that data outside of ajax, when i do console
my array, It is returning array, here is the screenshot:
Here is my code:
function getData(){
let surahArray = [];
// created empty variable
$.ajax({
url: 'http://mp3quran.net/api/_english.php',
type: 'get',
success: function(data){
let urlServer = data.reciters[112].Server;
let resUrl;
for(resUrl=1; resUrl <= 114; resUrl++){
resUrl = resUrl < 10 ? '00' + resUrl : '' + resUrl;
resUrl = (resUrl < 100 && resUrl > 9) ? '0' + resUrl : '' + resUrl;
surahArray.push(urlServer + '/' + resUrl + '.mp3');
// pushing array data to that empty array
}
},
error: function(err){
console.log(err);
}
});
let surahs = surahArray;
// working
console.log(surahs);
// not working
console.log(surahs[0]);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button onclick="getData()">Get Data</button>
If i do console.log(surahs)
It sis returning me array list, but when i do console.log(surahs[0])
, It's returning me undefined
in console
.
Please help me, where i am wrong?