user2639194
user2639194

Reputation: 11

jquery read in HTML file and return the file as an object-why doesn't it work?

I'm wondering if maybe this code doesn't work because you can't return a JQuery object from a function. This code doesn't work:

var HTML_FILE_URL = '/Solutions1.htm';
var strAll = $.get(HTML_FILE_URL, function (data) {
                      var fileDom = $(data);
                      return fileDom;
                });
 $("#qapagediv").append(strAll.html());

However, this code does work:

 var strAll = $.get(HTML_FILE_URL, function (data) {
         var fileDom = $(data);
         $("#qapagediv").append(fileDom);
         return fileDom;
  });

Upvotes: 1

Views: 62

Answers (2)

Louis Ricci
Louis Ricci

Reputation: 21086

Check the documentation for $.get() http://api.jquery.com/jQuery.get/ it doesn't return the value of a callback. Functions with callbacks for success generally run asynchronously.

You could perform your task inside of the callback function

$.get(...).done(function(data) { 
    var strAll = $(data);
    $("#qapagediv").append(strAll);
});

To do things like your first example you need to run your AJAX request synchronously. Synchronously means it's completed before execution moves on to the next line.

var strAll = null;
$.ajax({
    url: HTML_FILE_URL
    success: function(result) {
        strAll = $(data);
    },
    async: false
});
...
$("#qapagediv").append(strAll.html());

Upvotes: 0

kalley
kalley

Reputation: 18462

Your problem is that $.get returns a $.Deferred().promise(), not the return value from your callback.

Upvotes: 4

Related Questions