What is the method for executing embedded JavaScript within a .innerHTML output?

I encountered a similar issue in the past with an external file not executing properly.

To resolve this, I opted to dynamically load the file by creating the element in JavaScript and linking to it using the .src attribute instead of relying on a script tag in the HTML. Should I follow a similar approach in this case?

Here is the JavaScript code snippet that needs to be executed, which is inserted via .innerHTML of the body. Currently, it remains inactive on my page. Pay attention to the JSON data being passed as the second parameter to the set function. This data is constructed in PHP and sent to the client using AJAX POST.

<script type='text/javascript'>new Arc.Shared().set( 'tweet_data', [{"id":"1","0":"1","picture":"0","1":"0","name":"Test Account","2":"Test Account","tweet":"Hi","3":"Hi","time":"1338559048","4":"1338559048"},{"id":"1","0":"1","picture":"0","1":"0","name":"Test Account","2":"Test Account","tweet":"hi","3":"hi","time":"1338558809","4":"1338558809"},{"id":"1","0":"1","picture":"0","1":"0","name":"Test Account","2":"Test Account","tweet":"<a class=\"bookmark_tweet\" target=\"_blank\" href=\"http:\/\/ebay.com\">ebay <\/a>","3":"<a class=\"bookmark_tweet\" target=\"_blank\" href=\"http:\/\/ebay.com\">ebay <\/a>","time":"1338504456","4":"1338504456"},{"id":"1","0":"1","picture":"0","1":"0","name":"Test Account","2":"Test Account","tweet":"foo","3":"foo","time":"1338504225","4":"1338504225"},{"id":"1","0":"1","picture":"0","1":"0","name":"Test Account","2":"Test Account","tweet":"foo","3":"foo","time":"1338504222","4":"1338504222"},{"id":"1","0":"1","picture":"0","1":"0","name":"Test Account","2":"Test Account","tweet":"foo","3":"foo","time":"1338504220","4":"1338504220"},{"id":"1","0":"1","picture":"0","1":"0","name":"Test Account","2":"Test Account","tweet":"foo","3":"foo","time":"1338504217","4":"1338504217"}] );</script>

Additional Points:

Another way to avoid using eval:

var myCode = 'alert("Hey there?");';
 var myFucn = new Function(myCode);
 myFucn();

Answer №1

In order to execute AJAX injected JavaScript safely, one option is to use the "eval()" function. Another approach is to load the script using a

<script src='[your JS URL]'></script>
tag.

Answer №2

Following a different approach as mentioned in this discussion on Stack Overflow:

One method involves using the appendChild function to insert ajax responseText into the DOM. Here is an example:

function onSuccess() {
    src = document.createElement('script');
    src.innerHTML = this.responseText;
    document.body.appendChild(src);
}

Another technique is to use an external element to trigger the script execution, which is described in detail here.

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

Regular expression is used to limit input to integers only, specifically numbers between -130 and 30

Completed the regex for 0 to 50 ^(?:[1-9]|[1-4][0-9]|50)$ The current regex is functioning correctly. Next step is to create a regex that includes negative numbers, allowing for values between -130 and 30 without any decimal points. ...

Insert a JavaScript object into the rendered HTML using the componentDidMount lifecycle method

I'm trying to incorporate a JavaScript object into the template once the component has mounted for tracking purposes. Here is how I want the object to be rendered: var tracking = { pagename: 'page name', channel: 'lp&ap ...

Adaptive Website displayed within an iframe

Currently, I have a responsive website that can be viewed here. The main objective is to embed this site into an iframe while maintaining its responsiveness. I attempted embedding my site in JSFiddle for testing purposes, which you can see here. However ...

When querying a JSON array of objects in Greenplum PXF external table, an empty string is returned instead of the desired element

When accessing JSON data through an external table using the PXF JSON plugin in a multiline JSON table example, If we define the column as: "coordinates.values[0]" INTEGER, We can easily retrieve 8 from the JSON below: "coordinates":{ "type":"Poin ...

The ion-input border seems to be fluctuating as the keyboard appears on the screen

I'm currently working with Ionic 3 and experiencing an issue where the selected ion-input's border in the ion-content is shifting when the device keyboard appears on the screen. Here is a visual representation of the problem: https://i.stack.imgu ...

JQuery: Creating a visually striking screen flash

How can I make the window or page flash/blink using JQuery or plain JavaScript? I also want to get the tab to flash at the same time. Currently, the code I have is: var flash = true; var alert = setInterval(function(){ if (flash) //doFlash ...

Anonymous model specifications on Loopback.io

Can anonymous models be defined using the slc tools or manually in json? For instance, I have a specific model member and would like to create a reusable anonymous 'address' model that is directly added to the document without being stored in the ...

Utilizing AngularJS to filter prices within a specific range using a button

I am new to using angularjs and I am working on implementing a price range filter with nouislider for a list of products with different prices. I want the filtering to happen only after the user clicks on the filter button. Below is the HTML code for my " ...

I encountered a problem with the Javascript toggle menu collapsing feature

I have built a custom toggle menu using Javascript: $(document).ready(function() { $('.toggle').click(function () { if ($(this).hasClass("expanded")) { $(this).next().slideUp("fast"); } else { $(&apos ...

Deactivate additional fields when choosing an option from the drop-down selection menu

When designing a form with a select dropdown that displays various options, I encountered an issue. I want to disable certain fields if a specific option is chosen from the dropdown. For instance, if "Within Company" is selected in the transaction type, I ...

Fetching the webpage that contains AJAX elements

For a while now, I've been using VBA to fetch stock prices from the ASX website (www.asx.com.au). Unfortunately, my script is no longer functional due to a recent website update that incorporates javascripts to generate content. Consequently, the scr ...

What is the best way to exclude an external HTML file from being displayed on the home page?

shopping_cart.php <div id="main-container"> <div class="container"> <span class="top-label"> <span class="label-txt">Shopping Cart</span> </span> <div class="content-area"> <div class="con ...

Unexplainable space or padding issue detected in OwlCarousel grid gallery

There seems to be an unusual gap or margin at the bottom of each row section in this portfolio grid gallery that's running in OwlCarousel. You can view an example here. https://i.stack.imgur.com/NHOBd.png I've spent a lot of time trying to solv ...

Looking for PHP script to save a JSONArray sent from an Android app into a remote database

I need assistance with writing PHP code to store the contents of a local database onto a remote database. Currently, I am adding the database contents into a JSONArray as a custom object and converting it into a string. This string is then passed as a POST ...

SEO Optimized pagination for pages without modifying the URL

On my website, I utilize pagination to navigate to various event pages. However, search engines are not picking up the conferences on these pages. Take a look at the code snippet below... <a href="javascript:;" class="first" title="First" onclick="getC ...

Using Jquery to trim the data returned from the server response

Utilizing asp.net for obtaining the server response via JQuery AJAX in JSON format has been my approach. I've experimented with both JQuery.getJSON() and typical jQuery response methods, followed by conversion to JSON format using $.parseJSON. Howeve ...

Use .load() to set an image as background in the div

There is a block of code that is supposed to display images in a div with the class "img", but it isn't functioning correctly. Can you provide some guidance on how to fix this issue? <div class="other"><a href="/index1.html">Link1</a&g ...

Nested tables in Datatables retrieving child table rows based on parent table

I have been struggling for the past three days to get my nested Datatables working properly. I have a parent table called MAINtable and a child table called adjlinesTable. The issue I am facing is that all lines from the adjlinesTable are being drawn to ...

What should be placed in the viewRef: MapViewNativeComponentType parameter when utilizing React Native Maps in the current.fitToSuppliedMarkers function?

useEffect(() => { if(!origin || !destination) return; mapRef.current.fitToSuppliedMarkers(["origin", "destination"], { edgePadding: { top: 50, right: 50, bottom: 50, left: 50} }) }, [origin, destination]); I'm currently in t ...

Pass the values of both buttons to a different page using PHP

I am currently developing a system for a hospital. The data is sourced from an array and I need to pass the values from two buttons to another page. For example, on the initial page: 1 xyz First 2017-04-08 11:35:00 body checkup Generate Presc ...