Search code examples
javascripthtmljsonexternal

My external function from javascript doesnt load before html


Im developing a mobile application using INTEL XDK with bootstrap mainframe. I have the Html code and a few external js files with functions to run on it. For some reason the function dosmth() from the JS file doesnt load before the HTML so it gives me no result. (The function should return an array of strings). Can someone tell me what is wrong with my code. What am I missing.

HTML heading on including the file.

      <script src="js/file.js"></script>

This is the code on calling the function on my HTML file.

    <h4>
        <script type="text/javascript">
              document.write(dosmth());
         </script>
    </h4>

The code of the method in the js file.

        function getCities()
          {
            var url = file.api + "name";
             console.log(url);
             $.getJSON(url).done(function(response){
                              if (!response.length) {
                              console.warn("Empty");
              }
                          file.name = response;
                        $('body').trigger('name-data');
                           console.log(response);
                           return (response);
                    }.fail(function(data, status, error){
                       console.error("Something went wrong");
                                  });
                     }

Solution

  • Maybe this helps.

    First, make sure the HTML markup is selectable. For instance, indicate an id for this h4.

    <h4 id="cities"></h4>
    

    You also need to wait for the document to finish loading before calling the JS function:

    <script type="text/javascript">
         window.onload = function() {
             getCities();
         );
    </script>
    

    Instead of returning anything, we update the h4.

    function getCities()
    {
        var url = file.api + "name";
        $.getJSON(url).done(function(response){
            if (!response.length) {
                console.warn("Empty");
            }
            // don't know what these two lines are meant to do
            file.name = response;
            $('body').trigger('name-data');
            // update the h4 element
            $('#cities').html(response);
            // the next line was missing a ")" before ".fail"
        }).fail(function(data, status, error){
            console.error("Something went wrong");
        });
    }