31

How do I load the content of a file into a variable instead of the DOM using jQuery .load() method?

For example,

$("#logList").load("logFile", function(response){ });

Instead of loading the file into the #logList element of the DOM, I would like it to load into a variable.

2

2 Answers 2

40

load() is just a shortcut for $.get that atuomagically inserts the content into a DOM element, so do:

$.get("logFile", function(response) {
     var logfile = response;
});
Sign up to request clarification or add additional context in comments.

Comments

23

You can use $.get() to initiate a GET request. In the success callback, you can set the result to your variable:

var stuff;
$.get('logFile', function (response) {
    stuff = response;
});

Please note that this is an asynchronous operation. The callback function will run when the operation is completed, so commands after $.get(...) will be executed beforehand.

That's why the following will log undefined:

var stuff;
$.get('logFile', function (var) {
    stuff = var;
});
console.log(stuff); //undefined

2 Comments

You can't actually use 'var' as a variable name. function (var) => can be => function (data); stuff = data
Thank you very much for noting this was asynchronous, that one comment unlocked the whole issue I was having and lead me to learn about .done etc over here.

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.