Holla

I am using AJAX to load content into a section of my website. I would like the content that is loaded in to execute some javaScript. However, when i simply include it in the response, it doesn't get evaluated.
Say i request a page, test.htm. That page includes ONLY the following code:

<script language="javaScript">
  function testFunction(){
      alert("HELLO WORLD");
  }
  testFunction();
</script>

Should this function not execute, and alert "Hello world?"

Dani AI

Generated

AJAX responses do not automatically execute <script> blocks. As noted, simply inserting response HTML into the DOM won’t reliably run scripts; relying on eval is brittle and unsafe. The reliable pattern is: parse the returned HTML, insert the non-script markup into the page, then explicitly recreate and append real <script> elements so the browser executes them in order.

A concise, robust workflow:

  • Parse the response into a temporary DOM (a hidden DIV or DOMParser).
  • Extract all <script> elements and remove them from the markup before inserting the markup into the target container.
  • For each extracted script: if it has a src, create a new <script> element with that src and append it (load sequentially to preserve order); if it’s inline, create a new <script> element and set its text content, then append it to execute immediately.
  • Avoid eval for inline code coming from untrusted sources; watch for re-defined globals and event-handler collisions.

Example implementation (keeps execution order and handles external and inline scripts):

function insertHtmlAndRunScripts(html, container) {
  const tmp = document.createElement('div');
  tmp.innerHTML = html;
  const scripts = Array.from(tmp.querySelectorAll('script'));
  scripts.forEach(s => s.parentNode && s.parentNode.removeChild(s));
  container.innerHTML = tmp.innerHTML;
  (async () => {
    for (const s of scripts) {
      if (s.src) {
        await new Promise(resolve => {
          const sc = document.createElement('script');
          sc.src = s.src;
          sc.async = false;
          sc.onload = sc.onerror = resolve;
          document.head.appendChild(sc);
        });
      } else {
        const sc = document.createElement('script');
        sc.text = s.textContent;
        document.head.appendChild(sc);
        document.head.removeChild(sc);
      }
    }
  })();
}

Cautions: do not eval untrusted content; be careful about loading the same script multiple times; external script URLs added this way will be fetched by the browser (different from XHR/CORS behavior); for repeatedly loaded widgets, prefer serving JS as standalone files and loading them once. That explains why the testFunction in ’s response never produced an alert when pasted straight into an AJAX response.

Holla

I am using AJAX to load content into a section of my website. I would like the content that is loaded in to execute some javaScript. However, when i simply include it in the response, it doesn't get evaluated.
Say i request a page, test.htm. That page includes ONLY the following code:

<script language="javaScript">
  function testFunction(){
      alert("HELLO WORLD");
  }
  testFunction();
</script>

Should this function not execute, and alert "Hello world?"

No the function will not execute. If you want that to run the script you will need to call a function after your response to "eval" the script for you.

Your new function will need to find and execute the script in the DOM.

pseudo code below

//put your response in a div or something and use the div id to grab the tag with a name = to script
divId.getElementsByTagName("script")
loop...
eval(script.innerHTML)

Running this after you response will run all the scripts on your page.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.