0

I am trying to load jQuery using xmlhttrequest object

I have following code:

 loadDoc("https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js", myFunction1);

    function loadDoc(url, cFunction) {
      var xhttp;
      xhttp = new XMLHttpRequest();
      xhttp.onreadystatechange = function() {
        if (this.readyState == 4 && this.status == 200) {
          cFunction(this);
        }
      };
      xhttp.open("GET", url, true);
      xhttp.send();
    }

    function myFunction1(xhttp) {
      // action goes here
      $(document).ready(function() {
        alert('test');    
    });

    } 

I am getting the error:

(index):62 Uncaught ReferenceError: $ is not defined
    at myFunction1 ((index):62)
    at XMLHttpRequest.xhttp.onreadystatechange ((index):53)
    at loadDoc ((index):57)
    at window.onload ((index):46)

Any reason why this is happening?

I typically want to do it this way as I won't be able to use as I am within a CRM form.

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Stanza
  • 485
  • 1
  • 4
  • 17
  • 1
    If that request succeeds it will only return the text contents of the file...it won't execute it. Append a script tag instead. Makes no sense using ajax to do this – charlietfl Nov 21 '17 at 00:34

1 Answers1

0

Try to run this script on the console here and you will see that your code is excuted without problem. The problem with your code is that you are tring to use the $ sign of Jquery in this line

$(document).ready(function() {

but you are not realy initilize the Jquery library on the page so javascript does not recognize this sign.

If you want to include the Jquery library inside the page you should do it likt in this question - include jquery

The scion
  • 1,001
  • 9
  • 19