views:

27

answers:

2

I'm dynamically loading content into a div when the user clicks a link using this code:

function ahah(url, target) {
  document.getElementById(target).innerHTML = 'Opening form...';
  if (window.XMLHttpRequest) {
    req = new XMLHttpRequest();
  } else if (window.ActiveXObject) {
    req = new ActiveXObject("Microsoft.XMLHTTP");
  }
  if (req != undefined) {
    req.onreadystatechange = function() {ahahDone(url, target);};
    req.open("GET", url, true);
    req.send("");
  }
}  

function ahahDone(url, target) {
  if (req.readyState == 4) { // only if req is "loaded"
    if (req.status == 200) { // only if "OK"
      document.getElementById(target).innerHTML = req.responseText;
    } else {
      document.getElementById(target).innerHTML=" AHAH Error:\n"+ req.status + "\n" +req.statusText;
    }
  }
}

function load(name, div) {
    ahah(name,div);
    return false;
}

This works fine, however I can't get any javascript to work in this new content, such as a jquery datapicker, or even just a document.write hello world. The js in there in the code, just not working. I've loaded the content directly in a browser and it works fine.

I'm at loss, any ideas greatly appreciated!

A: 

Javascript has a protection mechanism, so that you cannot execute code in dynamically loaded content. So any code you download through AJAX cannot then be executed. This is probably a good idea (for security) but it does mean you have to find alternate ways to call new code - returning a control structure (in JSON) and then have the calling code interpret that structure and perform commands is the way I usually work with it.

Rudu
A: 

If you are using jquery anyways, might as well try using jquery.ajax(). You could include whatever scripts you need in the <head> and then call your datepicker or w/e in the callback function of your jquery ajax call.

dave
Good call, i'll try that.
Robimp