user_78361084
user_78361084

Reputation: 3928

Why does this function stop working when executed after an ajax call?

I have the following jsfiddle

<style>
  .line {
    fill: none;
    stroke: steelblue;
    stroke-width: 2px;
  }
</style>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script>
  var data = [{ "date": "1-May-10", "close": 2 }, { "date": "1-May-12", "close": 7 }];
  var result = { // a mock version of our response
    "javascript": ["https://cdnjs.cloudflare.com/ajax/libs/d3/4.13.0/d3.js", "https://cdn.jsdelivr.net/gh/nottoobadbutgoodname/tester/chart.js"
    ]
  }

  function loadAll(resultt) { // throwaway var resultt as we are using our mock result
    console.log("loading....");
    getMultiScripts = function (arr) {
      var _arr = $.map(arr, function (scr) {
        return $.getScript(scr);
      });
      _arr.push($.Deferred(function (deferred) {
        $(deferred.resolve);
      }));
      return $.when.apply($, _arr);
    }
    getMultiScripts(result.javascript.slice(0, -1)).done(function () {
      $("<script/>", {
        src: result.javascript[result.javascript.length - 1]
      }).appendTo("body");
    });
  }

  function main() {
    $(document).ready(function () {
      $.ajax({
        url: "http://127.0.0.1:8000",
        success: loadAll
      });
    });
  }

  main(); // doesn't work
  //loadAll(result); // works!
</script>

running loadAll(result) directly works but when I try it with an ajax call it fails silently. Essentially, the ajax call grabs some .js files that are then loaded. Running main will fetch the scripts but doesn't seem to execute them (status code for both is 200 but the status code for chart.js is greyed out when running main() but black when running loadAll()

EDIT:

This is weird. Since in the example I am just mocking the result I thought I'd try an experiment:

https://jsfiddle.net/rwzm4t75/4/

Basically, I turn it into a JSONP call and grab some random JSONP data and turn loadAll to the jsonCallback function. The chart is now loading consistently but, unfortunately, for the "real world" the result cannot be mocked and the data comes as JSON, not JSONP.

To be clear, I've tried a JSON response in my real app and JSONP. The JSON version will sometimes load but not consistently. The JSONP version always loads.

Upvotes: 2

Views: 91

Answers (1)

McBern
McBern

Reputation: 549

Try to execute main() inside document ready:

$(document).ready(function () {
    main();
});

function main() {
    $.ajax({
      url: "http://127.0.0.1:8000",
      dataType: 'JSON',
    })
    .done(function(result)){
       loadAll(result);
    });
}

Upvotes: 1

Related Questions