First, I grab HTML using jQuery's $.ajax function.
In the success function I alert it (this works correctly and shows an HTML string as expected);
Then I pass it in as a variable to another function, processHTML. But it's not working and says the variable is null. I confirm this with an alert.
var my = my || {};
jQuery(function ($) {
my.html = {
getHTML: function(url) {
$.ajax({
url: url,
dataType: "html",
success: function( myHTML ) {
alert(myHTML); // shows string, as expected
my.html.processHTML(myHTML); //returns null
}
});
},
processHTML: function ( myHTML ) {
alert(myHTML);
// do stuff and return myHTML
}
} // end of my.html object
}); // end of jQuery wrapper function
Why isn't the string getting passed from the success callback into the processHTML function? If I replace myHTML in the success callback with an actual string (<div>test</div>
), that gets successfully passed into the function.
Update: Here's the actual code, as requested. It is invoked by clicking a link with onclick="hey.mydoc.ajax2({source: 'http://www.mysite.com/mypage'})"
. This is also on JSFiddle but I get ReferenceError: Can't find variable: hey
when clicking the link, which doesn't happen on my site.
var hey = hey || {};
jQuery(function ($) {
hey.mydoc = {
//////////////////////////////////////////////////////
//////////////////////////////////////////////////////
//////////////////////////////////////////////////////
getHTML: function ( source ) {
$.ajax({
url: source,
dataType: "html",
beforeSend: function(){
},
success: function( myHTML ) {
alert('myHTML is '+myHTML );
hey.mydoc.processHTML( myHTML );
} // end of success function
});
}, // end of method
//////////////////////////////////////////////////////
//////////////////////////////////////////////////////
processHTML: function ( myHTML ) {
alert ('processHTML - ' + myHTML );
myHTML = $(myHTML);
myHTML.find('script').remove();
// and a bunch of other DOM manipulations...
var content = "<!DOCTYPE html><html>" + myHTML.html() + "</html>";
return content;
}, // end of method
//////////////////////////////////////////////////////
//////////////////////////////////////////////////////
ajax2: function ( options ){
$.ajax({
url: options.content,
dataType: "html",
success: function( myHTML ) {
alert('myHTML is '+myHTML ); // myHTML is string of html, as expected
var newHTML = hey.mydoc.processHTML( myHTML ); // myHTML not getting passed in
alert(newHTML);
} // end of success function
});
} // end of method
} // end of hey.mydoc namespace
}); //end of jQuery wrapper