0

I have a js file say test.js and I want to import and use JQuery in it. I don't have a HTML file and I don't want to create one either.

I want to execute my js file once the jQuery is loaded. My code is as follows:

 var data = *some data that I am passing to the url*

function include(filename, onload) {
    var head = document.getElementsByTagName('head')[0];
    var script = document.createElement('script');
    script.src = filename;
    script.type = 'text/javascript';
     script.onload = script.onreadystatechange = function() {
      if (script.readyState) {
        if (script.readyState === 'complete' || script.readyState === 'loaded') {
            script.onreadystatechange = null;                                                  
            onload();
        }
    } 
    else {
        onload();          
    }
};
head.appendChild(script);
}

 include('http://ajax.googleapis.com/ajax/libs/jquery/1.7.0/jquery.min.js', function() {
   $(document).ready(function() {
 $.ajax({
        url: "some url,
        type: 'POST',
        crossDomain: true,
        dataType: 'json',
        data: JSON.stringify(data),
        success: function(response) {
            var data = response.hits.total;
            console.log(data);
        },
        error: function() {
          console.log("failed");
          }
       });

  });

});

This gives me an error : "ReferenceError: document is not defined"

I am running my .js file in node. How should I import and use JQuery.js to use it in my .js code?

9
  • nodejs has no concept of a document, have you tried making that call without the $(document).ready(..) ? Commented Aug 30, 2016 at 20:09
  • This seems wrong. Is your goal to make a http-request using node.js? Commented Aug 30, 2016 at 20:10
  • yes, its still throwing an error at line var head = document.getElementsByTagName('head')[0]; Commented Aug 30, 2016 at 20:11
  • My goals is to make http-request using JQuery and I am testing it using node Commented Aug 30, 2016 at 20:12
  • 1
    Question for the author... Why would you want to use jQuery when you don't even have an html page? Commented Aug 30, 2016 at 20:21

1 Answer 1

1

Try using something like the request or elasticsearch modules (see npmjs.com). Node.js is different from JavaScript in the browser, so the AJAX/jquery stuff doesn't apply.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.