0

I have a js file where i declared a variable that i want to use in a script in the html

js file (controllerB.js)

var modalArticles = [];
$(document).ready(function () {
    $.ajax({
        url: "https://newsapi.org/v1/articles?source=google-news&sortBy=top&apiKey=*****"
    }).then(function (data) {

        modalArticles = data.articles;
    })
})

html file

<head>
<meta charset="utf-8" />
<title>News</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>

<script src="js/handlebars-v4.0.10.js"></script>
<script type="text/javascript" src="js/controllerB.js"></script>


</head>
<body></body>
<script type="text/javascript">
    console.log('print: ' + modalArticles);
</script>

modalArticles is empty in html

João Santos
  • 115
  • 2
  • 13

1 Answers1

2

Your variable is empty because it is only initialized at the point where your document is loaded. You fill the variable with a asynchronous request, so it's only then available, when the Promise is resolved.

If you want to display the content of your variable in your HTML, you could use jquery (according to your tags) to set the HTML of the element, which you want it to be displayed in, to set the content in the then method.

If you want it to be displayed in "#mydiv", you could do this:

.then(function(value){
   $('#mydiv').html(value);
})
Bernd Strehl
  • 2,852
  • 4
  • 24
  • 43
  • what im trying to do is create an array that i will iterate in the html , not just displaying the content over a div – João Santos May 31 '17 at 15:04
  • then iterate the values in the array in your `then` function and add the values to the DOM, or do whatever you want to do with them. – Bernd Strehl May 31 '17 at 15:12