This is happening because the ajax request takes some time to get the html and your return statement fires before the html is ready. Javascript code execution does not wait for your html to return. You can actually see this by removing the return and putting two alerts. Put one alert inside the success event and one where you have put your return statement. The second alert would alert before. So, even though your html is fetched, it is never actually returned successfully to the calling function because the return statement already fired by the time html is ready.
You can use a callback if you strictly want the function getHtml() to return (well actually call back) the html as an output, or else you can use the way suggested by Nick.
Here is how to use a callback:-
function getHTML(instance, current_path, dir,callback)
{
var htmlCode = '';
jQuery.ajax({
type: "POST",
url: "../wp-content/plugins/wp-filebrowser/jquery.php",
dataType: 'html',
data: {instance: instance, current_path: current_path, dir: dir},
success: function(html){
callback(html); //instead of a return
},
error: function(e) {
htmlCode = '[Error] ' + e;
}
});
}
Call the function like this -
getHTML(instance, current_path, dir,
function(html)
{
//Write code to use the html here - this will run when the getHTML() function does callback with the output html
}
);
Note the callback parameter in the function definition getHTML(instance, current_path, dir,callback) and the corresponding function(html){} part in the called function.
This way, you actually define:-
- the called function to
call back the caller function when the output is ready
- and the caller function to do something when it receives the
call back.