Search code examples
jquerydeferred

Why isn't the jQuery .done() not recognizing an external function


I have something like this:

  //works fine
  $.ajax("info.txt")
    .done(function(data) {
      console.log("works");
    })

I also have something like this:

  //throws an error, stating CheckIt() inside the .done() is not a function
  $.ajax("info.txt")
    .done(function(data) {
      CheckIt(data);
    });

  function CheckIt(da) {
    console.log("it works");
  }

Why am I receiving the error and how can I circumvent the error allowing me to use other functions.


Solution

  • It's likely that your ajax request is failing. If you replace done with always, it will always be called, even if the request fails.

    $.ajax("https://cat-fact.herokuapp.com/facts/random")
      .always(function(data) {
        CheckIt(data);
      });
    
    function CheckIt(da) {
      alert("it works");
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>