Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get this function to return value retrieved using jQuery.ajax?

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;
  }
like image 731
Steven Avatar asked Feb 26 '23 06:02

Steven


2 Answers

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.
like image 64
Sandeepan Nath Avatar answered Feb 28 '23 18:02

Sandeepan Nath


It's an asynchronous operation, so you can't really return like this...not without making the request synchronous (async: true option), but I advise against this...since it locks up the browser for the duration of the request. You can't return because the success callback, when asynchronous, doesn't happen until later after the request runs, so your htmlCode = html; code simply hasn't run yet.

It's a better approach to call what's needed from your success callback once you have the data ready, for example:

success: function(html){
  doSomethingWithHtml(html);
},

or more succinctly for that specific one-liner case:

success: doSomethingWithHtml,
like image 28
Nick Craver Avatar answered Feb 28 '23 18:02

Nick Craver