Unable to utilize JavaScript from the imported AJAX page XMLHttpRequest

I have implemented a bit of AJAX functionality using XMLhttpRequest, where it replaces a div and functions as expected.

However, I am facing difficulty in getting the JavaScript code in the included AJAX page to execute. Is there a way to run JavaScript from the AJAX page that is included?

For example, let's say mainpage.php contains a select form. Upon a change event in the select form, includepage.php is loaded into a div on the page and updates based on the selected option. While this setup works smoothly using xmlhttp, the challenge lies in executing JavaScript from the included page, such as displaying a simple alert box.

Unfortunately, I don't have any specific code to share, and I'm unsure if this is a standard behavior. I have searched for information on this but haven't found much help. Any guidance on how to run JavaScript from within an included AJAX page that replaces a div would be greatly appreciated.

Answer №1

When you include scripts in content using innerHTML, the browser does not automatically execute those scripts.

If you want the scripts to run, you must extract them from the content, retrieve their text, and then insert them into new scripts that are subsequently added to the document. As long as the scripts do not require immediate execution via document.write(), this method will function properly. jQuery and other libraries handle this process automatically when inserting HTML into the document.

For a demonstration of this process, view this example: http://jsfiddle.net/jfriend00/2tRQW/

// Insert dynamic content containing a script
// Simulate an AJAX call response
var s = 'Hello<s' + 'cript>alert("Hello");  document.getElementById("result").style.color = "red";</s' + 'cript>';
var obj = document.getElementById("result");
obj.innerHTML = s;

// Locate script tags within the dynamic content
var scripts = obj.getElementsByTagName("script");

// Create new script tags to receive the script content
// Copy the content and insert the new script tags into the document to ensure browser execution
var head = document.getElementsByTagName("head")[0];
for (var i = 0; i < scripts.length; i++) {
    var oldScript = scripts[i].parentNode.removeChild(scripts[i]);
    var newScript = document.createElement("script");
    newScript.type = "text/javascript";
    newScript.textContent = oldScript.textContent;
    head.appendChild(newScript);
}

Answer №2

It appears that the code is unfamiliar to you, correct?

Allow me to provide you with an example:

On a page called page1.aspx

There is a JavaScript function named abc()

You can now add this function to the main page and include a user control (uc)

Then call this function like so:

var aa=abc();

This will execute the abc function

Even if you have the function on two separate pages, you can still call it. When JavaScript is rendered in the browser, it's combined based on the files included on your page.

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

JavaScript and the importance of using commas in arrays

I am developing a system that displays text in a textarea when a checkbox is checked and removes the text when the checkbox is unchecked. The functionality is mostly working as intended, but I am facing an issue where commas remain in the textarea after un ...

Issues with Express js routing functionality and executing mysql queries

As I dive into learning Node and Express, I'm encountering issues with routing in Express. I aim to create a well-organized and modular code for handling routes, particularly when querying data from a MySQL database: Let's start with my app.js f ...

What is the best way to transform a UTC/GMT date and time into CST in Javascript? (CST specifically, not based on

Dealing with a tricky situation where backend data is always stored in UTC time while our front-end data is in CST. Unfortunately, I don't have access to the system handling this 'black box' conversion. Trying to replicate this setup in our ...

Animating a dotted border path in SVG for a progress bar effect

I am attempting to create an animation for a dotted SVG circle that resembles a progress bar, where it fills itself over a duration of 3 seconds. However, I am facing difficulties in achieving this effect with the dotted border. The current code I have doe ...

Seek within a popup window and refresh the content of a DIV element on the main page

Yet again, it's the late hours of the night and I find myself facing a seemingly simple issue that's causing quite the headache! Here's the scenario: I have a basic HTML form inside a Bootstrap modal. Upon submitting this form, an AJAX POST ...

Executing a JavaScript function to trigger a PHP script that saves data into a MySQL database

I have a button in my HTML file that, when clicked, should insert data into a database and then reload the page. I am calling a JavaScript function within the onclick event to handle this. Below is the JavaScript function: function grandFinale() { i ...

Handling errors in XMLHttpRequest using Axios in React JS

I am currently utilizing the REACT-JS framework for my FRONT-END development: Below is the action I am calling from REDUX-REACT export function UserLogin(values) { var headers = { 'Access-Control-Allow-Origin': '*', ...

Determine the difference between a CSS selector string and an XPath string

Developing a compact querying module (using js) for html is my current project, and I aim to create a versatile query(selector) function that can handle both css selectors and XPath selectors in string form. My dilemma lies in determining whether a given ...

Insert a span element before an HTML input using JavaScript

On my webpage, there is an html input inside a div. Here is what it looks like: <input type="text" class="form-control" placeholder="Barcode" role="barcode"> Using JavaScript only, I am trying to add the following code into the DOM above it: <s ...

Tips for incorporating a pause or delay into if-else statements

Trying to optimize my semi-automated JavaScript code so it runs at a slower pace. Currently, it fetches detailed data from 100 listings one by one at a speed of around 15 times per second. While this works well in some aspects, it makes tracking which elem ...

Adding color to characters, digits in an HTML file

Is it possible to individually style each letter, number, and symbol in an HTML document with a unique color? I am interested in creating a text editor that applies specific colors to each glyph for those who have grapheme-color synesthesia. While there ar ...

A simple guide on how to display a child object in a materialUI select dropdown from a parent object

I am developing a ReactJS application where I aim to showcase child objects from the parent object in a dropdown using materialUI select. Despite attempting to iterate over the object using the map() function, I haven't been able to retrieve values up ...

ES modules' `require()` functionality is not supported

Issue: Error [ERR_REQUIRE_ESM]: Must use import to load ES Module: D:\...\node_modules\normalize-url\index.js [0] require() of ES modules is not supported. [0] require() of D:\...\node_modules\normalize-url\index.js ...

AngularJS routing with html5mode causing 404 error when using htaccess

I am currently working on my very first angularjs application using version 1.6x, and I am encountering some 404 errors with my router. Here is how my router is set up: app.config(function($routeProvider, $locationProvider) { $locationProvider.html5M ...

Using Regex to detect recurrent (similar) patterns in jQuery <input> tags

I need assistance with ensuring that users input article numbers in the correct format, like this: ABC_ABC123; AB__B2A4; ABF_323WET; ... Currently, I have a regex pattern that works for one article number: var mask1 = /^([A-Z]{2})([A-Z|_]{1})_([A-Z0-9]{ ...

Adjusting the width of the rail in Material UI's vertical Slider component in React

After attempting to adjust the width and height of the rail property on the material ui slider I obtained from their website demo, I have encountered an issue with changing the thickness. import React from "react"; import { withStyles, makeStyles } from " ...

Issues with Javascript Arrays not adding objects with duplicate values

When objects have arrays with the same values, only one of them is considered. For example: data[2018][2][25] <-- this one gets ignored by the object data[2018][2][22] Sample Code: var date = new Date(); var data = {}; <?php $eventsNum = 3> &l ...

Tips for setting up a proxy with an enum

I am facing an issue with setting up a Proxy for an enum. Specifically, I have an enum where I want to assign a value to this.status using a Proxy. However, despite my expectations, the output "I have been set" does not appear in the console. Can anyone ex ...

What location is most ideal for incorporating JavaScript/Ajax within a document?

Sorry for the seemingly simple question, but I would appreciate some clarification from the experts. When it comes to the three options of placing JavaScript - head, $(document).ready, or body, which would be the optimal location for ajax that heavily rel ...

The cause of Interface A improperly extending Interface B errors in Typescript

Why does extending an interface by adding more properties make it non-assignable to a function accepting the base interface type? Shouldn't the overriding interface always have the properties that the function expects from the Base interface type? Th ...