"Troubleshooting the failure of the alert function to work properly when loading content

I am working on a webpage named index.html

 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml"><head><meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
 <title>Lufia</title>
 <script language="javascript" type="text/javascript">
 function ajax()
 {

var xmlhttp;
if (window.XMLHttpRequest)
  {
  xmlhttp=new XMLHttpRequest();
  }
else
  {
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }

xmlhttp.onreadystatechange=function()
  {if (xmlhttp.readyState==4 && xmlhttp.status==200)
   document.getElementById('mydiv').innerHTML=xmlhttp.responseText;
  }
  xmlhttp.open("GET",'welcome.html',true);
xmlhttp.send();
 }
 </script></head>
<body>


<button onclick="ajax();"></button><div id="mydiv"></div></body>
</html>

In addition, I also have another page called welcome.html

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml"><head><meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
 <title>Lufia</title>

<body onload="alert('ank');">welcome
</body>
</html>

The goal is to trigger an 'ank' alert when the welcome.html file is being loaded through ajax as there is an alert function written in the body's onload attribute of welcome.html

Answer №1

Initially, the HTML code you're attempting to insert is not valid. It lacks essential elements such as a root element, head, and has the title tag placed outside of the head section. Moreover, it does not meet the criteria of a document fragment that most individuals return when loading HTML through AJAX.

Consequently, the browser handles this situation by removing the new <body> tag, resulting in the event being unable to trigger.

Questioning the purpose behind this approach - when you already have the equivalent of onload function that successfully inserts HTML into your <div>. Utilize that functionality instead of complicating the process further.

Additionally, keep in mind that trying to add a <script> using innerHTML will not be effective.

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

The object filtering process is experiencing issues due to the presence of a null value in the column

I am trying to extract object data based on a specific value from an array. While the code snippet below works well when there are no null values, it fails to work properly when encountering null values in the column. For reference, you can check out this ...

Is there a way to prevent the window.status from appearing?

I currently have the following code snippet: <a class="button accessLink" id="loginLink" href="#" data-action="Login" data-dialog="access" data-disabled="false" data-entity="n/a" ...

Utilizing JavaScript's Facebook Connect feature on a Ruby on Rails website

My ruby-on-rails web application is in need of integrating "Facebook connect" functionality to enable users to share various activities on Facebook. Are there any Javascript methods I can use for this purpose? Any demos you can suggest? In addition, I wou ...

Enhancing Javascript with ES6 for nested for loop operations

Hey there, I have a question about converting a nested for loop into an Array map/ES6 way. How does that work when dealing with nested for loops? for (var i = 0; i < enemy.ships.length; i++) { for (var n = 0; n < enemy.ships[i].locat ...

Mastering the art of customizing classes and styles in material-ui (React)

I am facing a challenge with version 1.2.1 of material-ui. My goal is to make the AppBar component transparent by overriding its styles as per the documentation here. This is the code snippet I have been working on: import React, { Component } from ' ...

Is it possible that jQuery does not function properly with ids that are retrieved through an Ajax request?

Can this be verified? <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js" type="text/javascript"></script> <script> $(document).ready(function(){ $("#reset").click(function(){alert("hello");}); ...

What is the process for defining default prop data in Next.js?

Currently, I am in the process of developing a React/Next app with CRUD functionality. In regards to the update form, I have included the code below which is responsible for fetching existing data and updating it via an API. However, there seems to be a ma ...

Null value arising due to AJAX's asynchronous nature

I am facing an issue with a form that includes a select option displaying various choices. My goal is to retrieve the selected option and display it in a text box. The options are loaded using AJAX from an XML data source. When attempting to grab the sele ...

The problem with THREE JS OcclusionComposer: encountering "Cannot read properties of undefined (reading 'x')" error

I am attempting to replicate the Volumetric Lighting demonstration created by JMSWRNR but I am encountering difficulties with the Occlusion Composer. Since I am not well-versed in GLSL, debugging has proven to be quite challenging, especially for someone l ...

Display the data returned from a computed property PromiseResult using VueJS

After calculating the property shown below, it will output res, which is a Promise object. The reason I cannot place this script inside the created() or mounted() hook is due to the fact that this.selectedObject is null at that time. I am satisfied with t ...

Dynamically insert innerHTML content into table rows using JavaScript in PHP is a fantastic way to customize

Having trouble with innerHTML in this scenario, looking to achieve something along these lines: <table width="100%" border="0" id="table2"> <?php include("connection.php"); $sql=mysql_query("select* from b1"); while($res=mys ...

What steps should I take to fix the error "Unused left side of comma operator with no side effects.ts(2695)" in my React project?

import React from "react"; import { useRecoilState } from "recoil"; import { Industry, industryState } from "../atoms/industriesAtoms"; const manageIndustryData = () => { const [industryStateValue, setIndustryStateValue] ...

JavaScript is sending a variable to a .php file, which then returns data based on the variable. The information is displayed using JavaScript and AJAX, along with triggers set using the bind('input', function

Currently, I am attempting to create a form that automatically populates some input fields when there is a change. However, I am struggling to understand how to send the #url field to my PHP script. Any insights or suggestions would be greatly appreciated. ...

Determining the clicked node in a JavaScript environment

There are multiple spans with labels. <span class="viewEdit">View and edit class one.</span> <span class="viewEdit">View and edit class two.</span> <span class="viewEdit">View and edit class three.</span> <span clas ...

How can we wrap the Vuex store within a Vue plugin's install function?

I developed a plugin that utilizes Vuex for state management. // plugin.js import Vuex from "vuex"; import store from "./store.js"; export default { install(Vue, options) { const storeInstance = new Vuex.Store(store); Vue.pr ...

Having trouble with a peculiar for_of loop issue in Node.js: struggling to iterate correctly

Currently immersed in a Python project, I find myself in need of retrieving data from a Node.js API. Despite my limited knowledge of Node.js, I attempted to write some code for this purpose. Here is the code snippet: const SneaksAPI = require('sneaks ...

How to prevent v-menu from overlapping a navbar in Vue.js

Exploring the examples on the main page of Vuetify, we come across the v-menu component showcased in detail. Check it out here: https://vuetifyjs.com/en/components/menus/#accessibility If you activate any of the buttons to open the v-menu and then scroll ...

Tips for implementing FontAwesome in Nuxt3

I'm facing some issues trying to implement FontAwesome in my NuxtJS project, and for some unknown reasons, it's not working as expected. Let's take a look at my package.json: { "private": true, "scripts": { " ...

Conceal the URL and any parameters upon successful completion of AJAX request

In my ajax js code, the solonreport.jsp file returns a URL link that connects to a local report server and generates an Excel report. However, when using this link with the window.open(json.url) function, the link and parameters are visible to the user. ...

Only execute the NPM script if there is a staged JavaScript file

How can I ensure that an NPM script runs only when a JS file is staged, specifically after a pre-commit git hook (using Husky)? The scripts in my package.json are as follows: "scripts": { ... "test": "jest", "precommit": "npm test", ... }, ...