Script that was generated dynamically is failing to run

I have a situation where I am adding a script tag, along with other HTML content, to my current document after making an AJAX call. However, the script is not executing as expected.

//Function to handle response
function(responseText){
    document.getElementById('reportContainer').insertAdjacentHTML('afterbegin',responseText);
}

Here is an example of what the responseText might look like:

<h2>You are <em class="won">successful</em>!</h2>
<h3>Profits</h3>
... 
<script>
    alert('dgd');
</script>

All the HTML elements are being added to the document correctly, including the script tag, but the alert message is not showing up. What could be causing this issue?

Answer №1

Take a look at the code snippet below and use the function by following this:

var newElement = document.querySelector("#reportContainer");
exec_body_scripts(newElement);

Function Details:

exec_body_scripts = function(body_element) {
  // Locates and runs scripts within the body of a newly added element.
  // Necessary because innerHTML does not execute scripts.
  //
  // The argument 'body_element' represents an element in the DOM.

  function nodeName(element, name) {
    return element.nodeName && element.nodeName.toUpperCase() ===
              name.toUpperCase();
  };

  function evalScript(script_element) {
    var content = (script_element.text || script_element.textContent || script_element.innerHTML || ""),
        head = document.getElementsByTagName("head")[0] ||
                  document.documentElement,
        scriptTag = document.createElement("script");

    scriptTag.type = "text/javascript";
    try {
      // does not work on IE...
      scriptTag.appendChild(document.createTextNode(content));      
    } catch(error) {
      // Handling special case for IE
      scriptTag.text = content;
    }

    head.insertBefore(scriptTag, head.firstChild);
    head.removeChild(scriptTag);
  };

  // Main part of the function
  var scriptElements = [],
      currentScript,
      childNodes = body_element.childNodes,
      node,
      index;

  for (index = 0; childNodes[index]; index++) {
    node = childNodes[index];
    if (nodeName(node, "script") &&
      (!node.type || node.type.toLowerCase() === "text/javascript")) {
          scriptElements.push(node);
      }
  }

  for (index = 0; scriptElements[index]; index++) {
    currentScript = scriptElements[index];
    if (currentScript.parentNode) {currentScript.parentNode.removeChild(currentScript);}
    evalScript(scriptElements[index]);
  }
};

Answer №2

The function will not run correctly if you insert it into the DOM like this. Have you considered using jQuery instead? Using jQuery will ensure that the function executes properly:

$('#reportContainer').append('<script type="text/javascript">alert(123);</script>');

Answer №3

When making an Ajax call, the data received is either plain text or XML that can be added to the DOM as an HTML fragment. However, it is important to note that all JavaScript code is restricted for security purposes. There are several options available to handle this limitation, ranging from extracting a specific part of the responseText and utilizing the eval method (although not recommended due to being considered bad practice) to employing the jQuery.load method.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Display previous messages in React JS chat when scrolling upwards

https://i.sstatic.net/mcJUp.png I am currently working on a chat application, as depicted in the image. Once the chat is initiated, it automatically scrolls down to display the most recent messages. My goal is to implement a feature where when a user sc ...

Issue with data-ng-class function not being invoked

I'm currently working on a simple Angular project where I need to dynamically color list items based on a function called in data-ng-class. Below is an excerpt from my HTML file: <div> Rooms:<ul style="list-style:none;"> < ...

Convert the button element to an image

Can someone please explain how to dynamically change a button element into an image using javascript when it is clicked? For instance, changing a "Submit" button into an image of a check mark. ...

The resolution of Angular 8 resolver remains unresolved

I tried using console.log in both the constructor and ngOnInit() of Resolver but for some reason, they are not being logged. resolve:{serverResolver:ServerResolverDynamicDataService}}, console.log("ServerResolverDynamicDataService constructor"); console ...

There are occasional instances in Angular 6 when gapi is not defined

I am currently developing an app with Angular 6 that allows users to log in using the Google API. Although everything is working smoothly, I encounter a problem at times when the 'client' library fails to load and displays an error stating gapi i ...

The proper method to retrieve the parent function parameter within an inner JavaScript callback function

Consider the code snippet below. var exec = require('child_process').exec; var extraInfo = {'test':1,'passing':'test'}; runWithData(extraInfo); function runWithData(passedData) { exec('/Users/test/Deskto ...

Enhancing Child Elements with CSS - Evaluating Rating Systems

Is there a way to change the opacity of certain images inside my div when hovering over them? Specifically, I want the 4th image and the first three to have an opacity value of 1. I've looked into using nth-child but am unsure how to implement it for ...

Using AJAX in TYPO3's TCA forms to create dynamic dropdown menus

I have created two drop down lists in my TCA forms. The first one is called Campus and the second one is called Department. I want the options in the Department list to change based on the selection made in the Campus list. Essentially, the items in the De ...

Animating the dimensions of objects in THREEjs

In my project using THREE.js, I am aiming to create a captivating animation where an object gradually shrinks into nothingness. After exploring solutions on Three.js - Animate object size, I found methods to adjust the size of an object. However, the chan ...

Creating visual content on a website

I'm currently working on a project where I need to showcase the results of a numerical model I am operating. My goal is to gather user input in the form of latitude/longitude coordinates, utilize php (or a similar tool) to trigger a python script that ...

What is the best way to access a JSON Array in php without using any specified keys?

I'm dealing with a JSON object created in JavaScript and passed to PHP via AJAX. The issue I'm facing is that I can't figure out how to assign keys to each JSON object within the JSON array. Here's an example of how the JSON array looks ...

Attempting to output properties from an Express/Mongo API by utilizing a React.js frontend

I am currently in the process of developing a simplistic fictional sneaker application with the MERN stack. While I wouldn't classify myself as a beginner, I'm also not an expert. I successfully created the backend and generated a json rest-api. ...

Keeping JSP current with changes made to files on the client side

Currently, I am tackling a project that consists of two main components: a) A Java Application that runs on a client machine. b) A Web Application that is hosted on a web server. The Java Application generates results at random intervals. These results n ...

I'm experiencing an issue with uploading an image to Firebase as I continue to encounter an error message stating "task.on is not a function."

The console displays a message confirming a successful upload. const sendPost = () => { const id = uuid(); const storage = getStorage(); const storageRef = ref(storage, `posts/${id}`) const uploadTask = uploadString(storageRe ...

Is there a way to display sorting icons consistently and in a blue color for the currently selected sorting column in a React material-table component?

I recently used the material-table library to create a material table, but I am having trouble displaying the sorting icon continuously for all columns. In addition, I would like the color of the column that is currently sorted to be blue. If you want to ...

Dealing with audio bleed from a previous recording using fluent-ffmpeg

const Discord = require('discord.js'); const client = new Discord.Client(); const ffmpegInstaller = require('@ffmpeg-installer/ffmpeg'); const ffmpeg = require('fluent-ffmpeg'); ffmpeg.setFfmpegPath(ffmpegInstaller.path); co ...

Enhance link with dynamic content using an AJAX call

I need help appending a picture after a link with the same URL as the link. The current AJAX code is producing the following result: <a href="images/Draadloos.png" data-lightbox="gallerij"></a> Here is an example of what I would like to achie ...

Extracting data from website's table using JavaScript and opening the link in href

My goal is to extract the details page for each link found on this particular page. The link provides access to all the information required: PAGE However, I'm interested in extracting details from pages that have links like this: href="javascr ...

pagination functionality incorporated into element ui tables

Issue with Element UI: when a checkbox is selected and the page is changed, the selected rows' checkboxes are removed. I need to retain the selection items while paging so that users can select items from multiple pages without losing the selections f ...

Is it possible for me to activate a function on a different component using my header?

Hi there, I'm curious about how Vue routing and the tree structure work together. In my setup, I have a parent router that contains both my router-view and header at the same level. I want to be able to trigger some functions from my header component ...