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

Require assistance with understanding Google's website preview feature in search results

Recently, I've been pondering about Google's new feature that shows the website directly in the search results. However, I'm puzzled as to how they achieved this. Is it an iframe? Or maybe a PHP rendering of the page? Perhaps dynamic JavaScr ...

jQuery does not have the capability to access the href attribute through DOM manipulation

I've been trying to extract the href attribute from a link in my code and create a new link using that attribute. However, I'm facing an issue where the created link doesn't seem to work properly - it keeps showing a 404 error message like t ...

Breaking down a string and then retrieving elements from an array

Just diving into the world of Javascript and jQuery, so I have a simple query. I've got a date that I need to break down into a string and then display it as an array. var date = "12/10/2010"; var dateArray = date.split(/); $('#printbox') ...

developing a dynamic map with javascript

In the image provided, my concept is for it to initially be without a green tint. However, when the user hovers over specific areas, they would turn green and become clickable links. There are multiple areas in the image, with this being just one example. ...

Use angular js to dynamically load a template via an ajax request

I am trying to send an AJAX request in order to retrieve a JSP/HTML page for the templateUrl of a modal. Here is the code I have written: var modalInstance = $uibModal.open({ animation: $scope.animationsEnabled, te ...

Using ReactJS to create different behavior for checkboxes and rows in tables with Material-UI

I am looking to customize the functionality of checkboxes and table rows. Currently, clicking on a row also clicks the checkbox, and vice versa. What I would like to achieve is for clicking on a row to trigger a dialogue box, and for clicking on the chec ...

Manipulate the value of the <input> element when focused through JavaScript

After I focus on the input field, I was expecting to see Bond-Patterson, but instead, I am only getting Bond. What could be causing this discrepancy and how can it be fixed? $('input[name="surname"]').attr("onfocus", "this.placeholder='Bo ...

Regex fails to recognize repeated instances of a specific pattern

Currently, my goal is to create a JavaScript regex that can interpret instances of patterns like \123 and convert them into their corresponding ASCII values. For example, 65 should be replaced with A. If the backslash \ itself needs to be includ ...

Having trouble mocking Node fs Modules using Sinon

I am facing an issue with mocking the promises methods of the node fs module in my code. When my appData.ts file is executed, it calls the actual fs.promises.mkdir method instead of the mock function defined in \__tests__/appData.test.js. I suspect ...

Retrieve the Response object when an ASP.NET Button is clicked

Within my ASP.NET Webform, I have a server-side Button with an Onclick event registered on it. <asp:Button ID="UploadButton" CssClass="btn add btn-primary" runat="server" Text="Upload File" OnClick="UploadBut ...

Error: Incompatible property or method 'val' for Object in Microsoft JScript runtime

When making a json request, I want to display a specific div only if the result from the request is true. Currently encountering an error message as shown below. Can someone please assist me with finding a solution? Microsoft JScript runtime error: Obj ...

Does this Loop run synchronously?

Recently, I crafted this Loop to iterate through data retrieved from my CouchDB database. I am curious whether this Loop operates synchronously or if async/await is necessary for proper execution. database.view('test', 'getAllowedTracker&ap ...

Enhanced Search and Replace Techniques in HTML using jQuery and JavaScript

Although I have some experience with jQuery and Javascript, I am by no means an expert. I have been struggling to find a way to achieve my goal using minimal resources. Maybe you can assist me: This is what I am trying to accomplish: I would like to use ...

Utilize ASP.Net to Retrieve and Showcase RSS Feeds

Looking to read and display a specific feed on my website. Developed in C# using .NET 2. Attempted to follow this tutorial: Encountered the following error: A column named 'link' already belongs to this DataTable: cannot set a nested table n ...

Utilizing a JavaScript variable within a jQuery function as an attribute

var image = "path.png"; Is it possible to include the 'image' variable in the jQuery function like this? $('#mapfoto').prepend('<img id="theImg" src="http://path.gr/" + image />'); ...

Achieving the functionality of keeping the search query box and alphabetical search options visible on the page even after performing a search and displaying the results can be done by

I have set up a PHP page with search query field and alphabetical search options. When submitting the query, the results are displayed on the same page; however, I would like the results to show in the same location as the alphabetical search. Currently, ...

Tips for displaying lower quality images while initially downloading higher quality versions

I need to download and display a large image in an img tag. Since the image is not Progressive JPEG, it will render as it downloads. Is there a way to show a low-resolution version of the image while it fetches from the server using only CSS or an HTML p ...

Exploring and cycling through numerous links using Selenium WebDriver in a node.js environment

Decided to switch from Casper.js to Selenium for access to more tools. Currently trying to loop through multiple links and navigate them using node.js along with selenium-webdriver. Struggling to find any helpful documentation or examples, as I keep enco ...

The script is unable to locate the property 'indexOf' because it is undefined

Searching for a specific value in an array using ui-select to capture values. A function is created to verify the existence of the value, which works perfectly fine. However, the console displays multiple instances of the error 'Cannot read property & ...

Store the incoming documents from xmpp using the Strophe si-filetransfer feature

I am currently working on adding file transfer functionality to my web application using the strophe.si-filetransfer.js plugin. I have successfully received file details within an iq stanza. My inquiry is, how can I extract the file data from this iq stanz ...