views:

255

answers:

2

I am using Ajax to change the innerHtml of a div by using onclick on a link. I need to call a javascript function after the file is retrieved from the server and replaces the content of the div. How can i do this?

<div id="thisDiv">
<a href="this.php" onclick="ajaxfunction('thisfile.php','thisDiv');return false;">link</a>
...
</div>

The ajaxfunction function replaces the innerHtml of thisDiv with thisfile.php.

Thank you in advance!

A: 

If you want to do this asynchronously, the easiest way will be to just use a library. Prototype and jQuery are good choices. They both provide AJAX functions that take callback options, so that you can render different output in many different cases.

For example, you can perform some action on success, another on failure, another while the action is in progress, or actions for each HTML status code.

nfm
+2  A: 

I think that the best way, assuming that your AJAX requests are asynchronous, is to add a callback parameter to your function, that will be executed when the request ends.

Since you don't mention any JavaScript library either posted your ajaxfunction, I suppose that you might be doing raw XHR requests, if so, you could for example:

function ajaxfunction (url, elementId, callback) { 
  var xhr = new XMLHttpRequest();
  xhr.open("GET", url, true);
  xhr.onreadystatechange = function(){
    if ( xhr.readyState == 4 ) {
      if ( xhr.status == 200 ) {
        document.getElementById(elementId).innerHTML = xhr.responseText;
        callback(); // the content has been loaded to the DOM, executing callback
      } else {
        alert('error');
      }
    }
  };
  xhr.send(null);
}

And you could use the function like this (note that I don't recommend at all the use inline JavaScript event binding on HTML):

<a href="this.php" 
onclick="ajaxfunction('thisfile.php','thisDiv', otherFn);return false;">link</a>

The recommended way:

<a href="this.php" id="linkId">link</a>


window.onload = function () {
  // Event binding...
  document.getElementById('linkId').onclick = function () {
    ajaxfunction('thisfile.php','thisDiv', function () {
      alert('Content retrieved, this is the callback!');
      return false;
    });
  };
  // .... 
};

For a more comprehensive example, post the code of your ajaxfunction.

CMS
Thanks man - didn't catch that.
Andy Gaskell
You're welcome @Andy, happens often...
CMS
rock on that works - thanks!