I need to return dynamic loaded content. I thought this was the way to do it, but the function returns blank. What do I need to do in order to set htmlCode with the html code retrieved from jQuery.ajax?
// Get directory listing
function getHTML(instance, current_path, dir) {
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){
htmlCode = html;
},
error: function(e) {
htmlCode = '[Error] ' + e;
}
});
return htmlCode;
}
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
alertinside the success event and one where you have put your return statement. The secondalertwould 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
callbackif you strictly want the functiongetHtml()to return (well actuallycall back) the html as an output, or else you can use the way suggested by Nick.Here is how to use a callback:-
}
Call the function like this –
Note the
callbackparameter in the function definition getHTML(instance, current_path, dir,callback) and the correspondingfunction(html){}part in the called function.This way, you actually define:-
call backthe caller function when the output is readycall back.