Executing a dynamic webpage with JavaScript through AJAX and updating with innerHTML

Sending GET data with AJAX to another file, I include

echo "<script>alert('Something');</script>";
in the other file. This content is then dynamically displayed using AJAX.

var ajaxDisplay = document.getElementById('edit');
ajaxDisplay.innerHTML = ajaxRequest.responseText;

The above code puts the

<script>alert('Something');</script>
inside a div named edit. However, no alert is shown. How can I make it work?

I have a mix of HTML and JavaScript in my project. Below is a snippet of the code:

function ajaxFunctions(){
    var ajaxRequest;  // The variable responsible for enabling Ajax!

    try{
        // Compatible with Opera 8.0+, Firefox, Safari
        ajaxRequest = new XMLHttpRequest();
    } catch (e){
        // For Internet Explorer Browsers
        try{
            ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
        } catch (e) {
            try{
                ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
            } catch (e){
                // An error occurred
                alert("Your browser broke!");
                return false;
            }
        }
    }
    // Create a function to receive data from the server
    ajaxRequest.onreadystatechange = function(){
        if(ajaxRequest.readyState == 4){
            var ajaxDisplay = document.getElementById('edit');
            ajaxDisplay.innerHTML = ajaxRequest.responseText;
        }
    }

    var namef = document.getElementById('nameed').value;
    var queryString = "?namef=" + namef;
    ajaxRequest.open("GET", "try.php" + queryString, true);
    ajaxRequest.send(null);

}

Is it a good idea to locate the script tags and use eval? But how can I identify the script tags?

Answer №1

Instead of attempting to insert a script element in the DOM, simply make your script deliver this:

alert('Hello');

Then execute it using eval(response);. Another option is adding a script element with the src attribute pointing to the page that provides your JavaScript within the <head> (the recommended approach).

function loadScript(url) {
    var head = document.getElementsByTagName("head")[0];
    var script = document.createElement('script');
    script.type = 'text/javascript';
    script.src = url;
    head.appendChild(script);
}

Remember that this method won't function for cross-domain requests--the script must originate from the same source as the page where your code is executed. To overcome this limitation, you'll need to utilize a callback.

Answer №2

It seems like the main purpose of using innerHTML is to trigger the execution of JavaScript code. However, once the page has finished loading, the JavaScript doesn't automatically recognize and process any new changes made to the text. In this scenario, what you need is a callback function:

http://api.jquery.com/jQuery.ajax/

I'm not very familiar with jQuery, but it appears that you can simply include a 'complete' property in the settings object when making the .ajax() call, like this:

 $.ajax({
   // ......

   complete: function(){
     alert('Something');
   }

   // ......
 });

With this setup, the callback function will be triggered once the ajax call is finished. You also have the option to choose other events like success or failure if you want to connect your code to different events.

Answer №3

How can the script tags be located?

The method would involve using

parent.getElementsByTagName('script')
and then evaluating the data of the text node inside.

However, it's worth noting that adding content with script tags can be unpredictable and may behave differently on various browsers. For example, Internet Explorer will run the script as soon as the script node is added to any parent, whether it's in the document or not. On the other hand, Firefox will execute the script when a subtree containing the script is added to a node within the document. This difference in behavior could lead to scripts being executed multiple times on certain browsers, or at incorrect timings after further page manipulation.

To avoid such issues, it's advisable to separate the script that needs to be executed from any HTML content. One way to do this is by using a JSON object that contains both the HTML and JavaScript separately.

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

Why does Safari browser keep showing NAN instead of a value?

In my quest to calculate the difference between two times in Safari browser, I encountered an issue. The code works perfectly fine in Chrome, but in Safari, it returns NAN. When I run the application for the first time, I save today's date. On subsequ ...

Running an Express middleware function

While watching a tutorial on the Express framework, I came across some interesting code used by the instructor for handling requests. Here is how the route is set up: router.route('/').post(authController.restrictTo('admin', 'l ...

xhttp.load path for server-side module

I'm currently working on developing a node package and in my JavaScript code, I have the following: const calcHtml = './calc.html'; const xhttp = new XMLHttpRequest(); xhttp.onreadystatechange = function () { if (this.readyState == 4) { ...

"Utilizing an if-else statement within a forEach loop

I have an array of ages and I want to determine the age range for each age along with the count, then push it into my object. The issue I am facing is that if there are multiple ages in the same range, it gets pushed twice. I only want to push it once and ...

Concealing the flexslider in Angular when accessing the main URL

I need to hide a div with flexslider in it on the root page using ng-hide. The issue is that the images do not load when navigating to another path. Here is how my index.html is structured: <ul> <li><a href="#/">Root</a> ...

An unforeseen issue arose while trying to update the data in a Chart.js chart within a Vue application

I am currently utilizing Chart.js version 3.5 along with Vue 3. After successfully creating a chart, I attempted to trigger a data change within a Vue method. However, I encountered an issue that displayed the following error message: "Uncaught TypeError: ...

The resolver function is ineffective when dealing with promise objects in Node.js

When attempting to utilize the Promise function in Node.js for file reading, unexpectedly the return promise resulted in {}. The sample code is provided below: http.createServer(function(req, res) { var readPath = __dirname + '/users.json'; ...

Enhance User Experience with Ajax Toolkit and Jquery Controls

<script language="javascript" type="text/javascript"> $(document).ready(function() { $("#TextBox1").click(function() { alert("Awesome!") }); }); </script> <asp:ToolkitScriptManager ID="ToolkitScriptManager1 ...

Using JavaScript to set a constant variable for dynamically changing the background image URL

I am trying to implement a feature where clicking a button will change the background of my HTML file, and then revert back to the original background when clicked again. To achieve this, I have set up a map containing key/value pairs. The first pair cons ...

Content Security Policy in Firefox Extension blocking local DataTables js

After downloading the js for DataTables, I attempted to load it onto my Firefox extension but encountered a Content Security Policy block: Content Security Policy: The page’s settings blocked the loading of a resource at self (“default-src moz-ext ...

The date of posting will always be '0000-00-00 00:00:00'

I'm experiencing an issue with my JavaScript code for writing reviews. Previously, it worked fine, but now the 'datePosted' column consistently outputs the default '0000-00-00 00:00:00'. writeReview(request, respond) { va ...

Using JQUERY to execute a callback function after an AJAX request is completed

I encountered a situation where I have the following code snippet: <a onclick="$('.element').hide(0); doMyMethod(_element = $(this));"></a> The doMyMethod() function is actually an ajax request. What I am trying to accomplish is to ...

encountering difficulties with installing dependencies using yarn or npm

After cloning a repository, I attempted to install the dependencies using npm install or yarn but encountered the following errors: For Yarn: https://gyazo.com/2fdf52c4956df2e565cc0b1cedf24628 For npm install: https://gyazo.com/a1d197e9ead89dbe4a7d3c5b8f ...

Angular 2 dropdown list that allows users to add a personalized value in the HTML code

Here is the scenario I am dealing with We are displaying a fixed dropdown list to the user For example, a dropdown list has 4 options such as apple, orange, grape, pineapple and 'create your own' If the user is not satisfied with the provided ...

Creating a JavaScript script to implement a CAPTCHA feature on Google Forms

I'm looking to implement a JavaScript solution that can prevent spam on Google Forms. The idea is as follows: Generate a random number a between 1 and 1000; Generate another random number b between 1 and 1000; Obtain input from the user, storing it a ...

What is the best way to show an array within a string using javascript?

Take a look at this code snippet : const names = ["Alex", "John", "Kit", "Lenny"]; for(let i = 0; i < 4; i++) { $("body").append("<p>" + names[i] + "</p>'); }; Can you figure out how to dynamically add each item in the 'names&a ...

The Ajax request header is set to content-type application/json on the development server, but on the production server it is

Operating a Drupal website on a LAMP stack. Utilizing the Advanced Poll module, where votes and canceled votes are handled through ajax. Everything runs smoothly on my development server; however, when transitioning to the production server, I encounter a ...

Obtaining the "category" and "name" from a stacked bar chart using the Highchart OnClick event

I am working with a Highchart stacked chart that includes a category and dataset structured as shown below: categories =["Clark","Steven","Steve","Robert","Max"] series =[{ name: "Wins" data: [0, 0, 0, 0, 0] }, { name: "Losses" data: [0, 0, 0, 0, 0] }, { ...

What is the best way to manage multiple arrays?

There is an array containing multiple arrays within it. I am trying to locate the specific sub-array that contains an object with name: "tax-payer-identification". Once found, I need to set the variable's value from required: true to false. ...

Clear the disabled input value in VueJS

My goal is to have the input disabled and empty. If the LEVEL2 input is empty, then both LEVEL3 and LEVEL4 should also be disabled and empty. If the LEVEL3 input is empty, then LEVEL4 should be disabled and empty. The disabled code is functioning properl ...