Learn how to call JavaScript code from an HTML file using Ajax

I am encountering an issue with my website. The index.html page contains JavaScript code that triggers an AJAX request to show the content of other.html inside a div in index.html.

However, despite the other.html loading correctly, the JavaScript code within it does not work as expected. Specifically, I have a simple script that should display an alert message saying "hello."

Here is an excerpt of the code:

index.html:

<html>
<head>
<script src=main.js></script>
</head>

<body>
<div id="to_change">bla bla bla</div>
<div id="button">click me</div>
</body>
<html>

main.js:

...
...
function sendRequest() {
    request.open("GET", "other.html", true);
    request.onreadystatechange = function(){
        if(request.readyState == 4 && request.status == 200){

            var response = request.responseText;

            if(response) {
                document.getElementById("to_change").innerHTML = response;
            }
        }
    }
    request.send(null);
}

...button.click(...sendRequest...);
...
...

other.html

<script type=...>alert("hello");</script>
<div>text text text text</div>

If anyone has insight into why the JavaScript code in other.html is not functioning properly when loaded into index.html, your help would be greatly appreciated. Thank you.

Answer №1

When the JavaScript is loading but the function call is not executing.

It seems like the functions are not being called within any event triggers.

<BUTTON onClick="myFunction()">

You can try calling the function like this, using any event trigger you prefer.

Answer №2

When working on the "other.html" file, be sure to eliminate any instances of the '<doctype...>', '<html>', and '<body>' tags if they happen to be included.

Answer №3

In order to execute the scripts manually, you can follow these steps:

// ...
if (response) {
  var elementToModify=document.getElementById("element_to_modify"), scripts, index;
  elementToModify.innerHTML = response;
  scripts = elementToModify.getElementsByTagName('script');
  for (index=0; index<scripts.length; index++) {
    eval(scripts[index].innerHTML);
  }
}

Keep in mind that using eval is considered unsafe, so proceed with caution...

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

Struggling to convert a JSON file into a TableView within a JavaScript application developed with Appcelerator

Trying to display a JSON file in a table using JavaScript and Appcelerator is proving to be quite a challenge. The output appears as an empty table when compiled to an example page. As someone relatively new to JavaScript and JSON, I'm seeking guidanc ...

Error message: "Property undefined when Angular attempts to call a function from jQuery/JavaScript."

I'm currently attempting to invoke an angular controller from my JavaScript code. This is my first encounter with Angular and I must admit, I'm feeling a bit overwhelmed! I've been following this example: Unfortunately, when testing it out ...

employ identical components in v-if and v-else

Currently, I am in the process of designing a login/register page using Vue. The layout includes separate tabs for both login and registration purposes. Here is a snippet of my template code: <transition v-bind:name="TabEffect"> <div ...

Updating Arrays in Node.js isn't happening as expected

Hello, I have a function that I am calling from my controller like this: var getLastPoll = await socketModel. getPollOptionsByPollId(data.poll_id); but the controller is returning an empty array as a result. However, when I log the result in my model, ...

IE11 experiences frequent crashes when running a web application utilizing the Kendo framework and JavaScript

I am experiencing difficulties with my ASP.NET MVC application that utilizes Kendo UI and jQuery. Specifically, when using Internet Explorer 11, the browser crashes after a short period of usage. The crash does not seem to be linked to any specific areas o ...

JavaScript is unresponsive and fails to display

I attempted to incorporate my initial Javascript snippet into a browser to observe its functionality. However, upon adding these lines directly into the body of my HTML code (even though I am aware that there are more efficient methods), no visible changes ...

The dynamic table rows are appearing out of order in the DOM

success: function (data, status) { var header = $("#MainDiv"); header.html(null); var headertemplate = $("<table class='searchlistbody'><tr></th><th>Name</th></tr>"); ...

Encountering an issue with googleapis in Vue.js: Error - The argument labeled as "original" must be of type Function

Attempting to retrieve rows from a Google Spreadsheet using googleapis for a Vue project. I have set up the necessary project and service account credentials in the Google console. However, upon clicking the button, I encounter this error: TypeError: The " ...

Encountering ENOENT error when accessing view file in NodeJS and Express

I've encountered a strange issue with my nodeJS application after refactoring it. The app launches without any problems, the API responds correctly. However, when I attempt to access "/", I receive the following error: Error: ENOENT, stat '/view ...

"Encountered a problem when trying to access file with node

An error has occurred: module.js:471 throw err; ^ Error: Module not found at '/Users/vinclo/app.js' at Function.Module._resolveFilename (module.js:469:15) at Function.Module._load (module.js:417:25) at Module.runMain (module.js:604:10) at run ( ...

Incorporating z-index into weekly rows within the FullCalendar interface

I'm facing an issue where my detail dropdowns on events are being cropped by the following row. Is there a solution to adjust the z-index of each week row (.fc-row) in the monthly view, arranging them in descending order? For example, setting the z-i ...

Having difficulties fetching the post content in Wordpress using AJAX

I am currently working on ajaxifying my Wordpress theme by utilizing the ajax-in-WordPress method as detailed on this page. However, I am encountering an issue when attempting to retrieve the content of a post using get_the_content function within function ...

Can you explain the error message "a.split is not a function" in an Angular context?

My Angular application is encountering an error upon page load. The error message displayed is as follows: angular-amin.js:122 TypeError: a.split is not a function at r (angular-amin.js:186) at m.$digest (angular-amin.js:145) at m.$apply (angular-ami ...

What is the best way to ensure Leaflet-Search functionality remains active even when a layerGroup is toggled off using L.control.layers

I am encountering challenges while using the Leaflet.Control.Search plugin by Stefano Cudini in conjunction with Leaflet's built-in function L.control.layers. When all layers are active, there are no issues with locating a specific area. However, wh ...

Heroku Internal Server Error with NextJs version 5.0.0

Below are the scripts that I am using: "scripts": { "dev": "node server.js", "build": "next build", "start": "NODE_ENV=production node server.js", "heroku-postbuild": "next build" }, This is the content of my procfile: web: npm start ...

Tips for displaying personalized data with MUI DatePicker

I need to create a React TypeScript component that displays a MUI DatePicker. When a new date is selected, I want a custom component (called <Badge>) to appear in the value field. Previously, I was able to achieve this with MUI Select: return ( ...

Having trouble with the parent folder functionality in JavaScript?

I am facing a challenge with my website's structure as I have an old setup that needs to be updated. http://localhost/enc/pdfs/ : This directory contains some html files that are uploaded via ajax to be displayed on a tabbed div using: var Tabs ...

On Internet Explorer 9, the window.open function is causing a new window to open up with

I am having an issue with redirecting my form to another page in a new window using window.open(). The problem I'm encountering is that when the new window opens, it appears blank and the original browser window redirects to the intended page for the ...

Tips for passing an array between components in Angular 2

My goal is to create a to-do list with multiple components. Initially, I have 2 components and plan to add more later. I will be sharing an array of tasks using the Tache class. Navbar Component import { Component } from '@angular/core'; impor ...

An issue occurred while attempting to access the Stripe checkout page

While working on my e-commerce website using next.js and stripe checkout, I encountered an error during the checkout process. I am utilizing the use-shopping-cart package, but suspect it may be causing the following response error from stripe-checkout: & ...