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.

kapa
  • 77,694
  • 21
  • 158
  • 175
Yetimwork Beyene
  • 2,239
  • 5
  • 27
  • 33
  • Don't use `.load()` then, use another method http://api.jquery.com/category/ajax/shorthand-methods/. – Felix Kling Jul 20 '12 at 16:27
  • This should have been included with [your last question](http://stackoverflow.com/questions/11582920/how-to-check-if-file-is-empty-before-loading-using-jquery-load-method) – MrOBrian Jul 20 '12 at 16:28

2 Answers2

39

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;
});
adeneo
  • 312,895
  • 29
  • 395
  • 388
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
kapa
  • 77,694
  • 21
  • 158
  • 175
  • You can't actually use 'var' as a variable name. function (var) => can be => function (data); stuff = data – Michael Nelles Sep 16 '19 at 14:21
  • 1
    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](https://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-asynchronous-call). – Alan Nov 21 '21 at 14:57