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

What factors cause variations in script behavior related to the DOM across different browsers?

When looking at the code below, it's evident that its behavior can vary depending on the browser being used. It appears that there are instances where the DOM is not fully loaded despite using $(document).ready or similar checks. In Firefox, the "els ...

How can I create a static navigation bar and sidebar using Bootstrap 4?

Currently, I am utilizing HTML, Javascript, Bootstrap, and CSS to develop a fixed navbar and sidebar for our system. My objective is to ensure that the navbar and sidebar remain fixed even when users scroll down the page, while also maintaining responsiven ...

Challenges arise when attempting to authenticate a user with password.js

Currently, I am working on implementing validation using passport.js and ES6. Below is the validation function that I have created: passport.use(new BasicStrategy( function(login, password, callback) { User.findOne({ login: login }).select(&a ...

Redux: utilizing yield within an unrecognized function

Hey there! I am brand new to Reudx-Saga and have been experimenting with it for the past few days. I feel pretty comfortable with generators, actions, redux-stores, sagas, and other concepts. Overall, I have a good amount of experience with JavaScript. C ...

Transforming user-entered date/time information across timezones into a UTC timezone using Moment JS

When working on my Node.js application, I encounter a scenario where a user inputs a date, time, and timezone separately. To ensure the date is saved without any offset adjustments (making it timezone-independent), I am utilizing Moment Timezone library. ...

What is the method for formatting within the <textarea> element?

While working on developing a comment system, I recently made the discovery that text areas cannot be formatted to retain paragraphs, line breaks, etc. This was particularly noticeable when comparing sites like StackOverflow, which uses a text editor inste ...

AngularJS encountered an error following a successful GET request

I'm attempting to retrieve data from the server using this code snippet. $scope.get_file_list = function() { delete $http.defaults.headers.common['X-Requested-With']; //We don't want OPTIONS but GET request $htt ...

jQuery autosave experiencing unexpected issues

I have encountered an issue where a couple of scripts that work perfectly on their own, do not function as expected when used together. Here is the code snippet along with an explanation of the problem: Autosave Function: <script> function auto ...

Retrieving ng-repeat object in Angular

How can I retrieve the current object from an ng-repeat on ng-click without using $index? The $index method is giving me the wrong index due to my use of orderBy. Ideally, I would like to be able to click on the object (thumbnail) and have $scope.activePer ...

Automatically integrating Nivo Lightbox into your website

I incorporated Nivo Lightbox into my website, seamlessly integrating all images with the plugin using the following code: <div class="portfolio-item"> <div class="portfolio-thumb "> <a class="lightbox" data-lightbox-type="ajax" title="Strat ...

Am I implementing the Vue.JS onChange function correctly?

After selecting an option from mod_accs_Role_ID, how can I display the corresponding data stored in the database based on that selection? For example, if I select 1 in mod_accs_Role_ID, then the role_Name 'Hello' should be displayed. <div clas ...

What could be causing the second switchMap to be triggered repeatedly upon subscription?

Check out the code snippet below for reproducing the issue: import { defer, BehaviorSubject, of } from "rxjs"; import { shareReplay, switchMap } from "rxjs/operators"; const oneRandomNumber = defer(() => of(Math.floor(Math.random() ...

What is the best way to access the id attribute of a <td> element within a <tr> using jQuery?

Can someone assist me with this issue? Is there a way to get the ID of the first or second td element instead of using a loop? Here is an example: "<tr class='test_point' id="+fileName+"><td><img src='"+ROOT_PATH+"/assets/d ...

Performing a Jquery ajax post to an MVC2 action

I have a script set up to send a POST request to an endpoint, and it seems like the routing is correct as it hits the breakpoint on the server. $(document).ready(function() { var o = new Object(); o.message = 'Hi from the page'; $.ajax({ ...

Why am I encountering difficulties connecting to the Socket IO object in Node.js using Express?

Encountering a strange issue on the remote server side where everything works fine locally with a self-signed cert over https. However, when moving the code to the server, it works locally but not remotely. A node app is created and hosted on the server u ...

npm command syntax to accept multiple arguments

Struggling to pass arguments in an npm command and utilize them in my script For instance: npm run test -b chrome -e QA "scripts": { "test": "something.js ./xyz/abc/cdf --something \"{\\\"browser\\\": \&bsol ...

JavaScript: void(0), Internet Explorer 6, and SWFAddress are all important components

Hello there, We are on the verge of launching a secure website (regrettably, we cannot provide the URL) and have come across a rather obscure bug in IE6 that I am hoping someone may have experienced or could shed some light on. This issue only arises when ...

can you explain the concept of a backing instance in react?

Although the concept of a "backing instance" is frequently mentioned in React documentation, I found it difficult to grasp its meaning. According to the React docs: In order to interact with the browser, you need a reference to a DOM node. By attaching ...

Tips for utilizing Async/Await within an expressjs router

Having trouble with Async/Await in my Nodejs project. I'm a beginner with Nodejs and facing an issue connecting to my mongodb collection through my repository. When I integrate my controller with the repository, I end up getting a null response. Take ...

Which option is better: installing plotly.js or plotly.js-dist using npm?

When it comes to plotly.js and plotly.js-dist, what exactly sets these two packages apart from each other? Notably, the installation instructions for plotly.js on npmjs.org specify running 'npm install plotly.js-dist' - why is this necessary? W ...