Steps for embedding a webpage within a div element

I am facing an issue while trying to load a web page within a div using an ajax call. Unfortunately, it's not working as expected and displaying the following error message:

jquery.min.js:2 [Deprecation] Synchronous XMLHttpRequest on the main thread is deprecated because of its detrimental effects to the end user's experience

Can anyone provide guidance on resolving this problem?

<div class="warper">
    <div class="menu">
        <a href="#" data-target="home">Home</a>
        <a href="#" data-target="pageOne">Page One</a>
        <a href="#" data-target="pageTwo"> Page Two</a>
        <a href="#" data-target="pageThree">Page Three</a>
    </div>



  <div id="content"></div>


<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>

<script>
    $(document).ready(function () {

        $("#content").load('home.html');
        // Set trigger and container variables
        var trigger = $('.menu a'),
            container = $('#content');

        // Fire on click
        trigger.on('click', function () {
            // Set $this for re-use. Set target from data attribute
            var $this = $(this),
                target = $this.data('target');

            // Load target page into container
            container.load(target + '.html');

            // Stop normal link behavior
            return false;
        });
    });
</script>

Answer №1

To clarify, the goal here is to insert content into a div, not an entire webpage. A webpage would have its own document and DOM, requiring an <iframe>.

Your issue may stem from using .data() instead of .attr(). In my solution, I utilize vanilla JavaScript's .getAttribute(), which achieves the same result without needing an additional jQuery call. Essentially, your code appears to be attempting to:

container.load(undefined + '.html');

I personally have not used the load method in this manner (the fact that it was overloaded for both event handling and ajax surprises me). A possible implementation could resemble the following example:

<script>
  $('#content').load('home.html');

  $('.menu').on('click', 'a', function (e) {
    e.preventDefault(); //prevent normal link behavior

    $('#content').load(this.getAttribute('data-target') + '.html');
  });
</script>

Furthermore, if your script resides at the bottom of the <body>, there is no need for $(document).ready(), as the code will only execute once the document has finished loading.

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

Encountering a 500 Error When Sending Data to ASMX Web Service Using jQuery: "Invalid Response Format Error 500"

Recently, I created a webservice located at . This webservice is practically identical to a script I quickly put together using jQuery to send mail via POST method. The script is quite straightforward: function ContactSubmit() { var Name = $('input: ...

Encounter a parameter validation error

Just a quick question. I have a JS function that takes a parameter as input. If the passed value happens to be NULL, I want to handle it accordingly. However, my limited experience with JS is making it difficult for me to use the correct syntax. Here' ...

Asynchronous function nested within a loop

Hello there! I am currently working on converting a SQLite database to NeDb using the following code snippet: const sqliteJSON = require('sqlite-json'); const Datastore = require('nedb') const exporter = sqliteJSON('etecsa.db&apo ...

Allowing Cross-Origin Resource Sharing on an Express Server hosted using Firebase Cloud Functions

Hey there, I have a simple Express setup on Firebase, shown below: import { onRequest } from 'firebase-functions/v2/https'; import express from 'express'; import bodyParser from 'body-parser'; import router from './router ...

Trouble with Map method not displaying data in Next.js

I am currently working on a Map Method but facing an issue. The data 1,2,3,4,5 is successfully displayed in the console.log, but not showing on the website. import React from 'react' export default function secretStashScreen() { const numbers = ...

What is the best way to generate JSX from a callback function in ChartJS?

I am currently utilizing react-chartjs-2 within a React application and I am interested in incorporating JSX code into the Y axis. However, when attempting to do so, it only shows [Object object]. const chart = new Chart(ctx, { type: 'line', ...

Unlocking the secrets to obtaining a socket.io client

I encountered an error when trying to set up a socket.io server and client. The error I received on the client side was: Failed to load resource:http://localhost:3000/socket.io/?EIO=4&transport=polling&t=OK-egu3 the server responded with a status o ...

The display of 'App' seems to be experiencing issues within the render method

Can someone help me with this issue? I am encountering the following error: Uncaught Error: Invariant Violation: Element type is invalid - expected a string for built-in components or a class/function for composite components, but received an object. Bel ...

What is the best way to format the date in an input tag to comply with ISO standards (ex: 2017-06-17T21:35:07

Here is an example of an input tag: <input type="datetime-local" class="datepicker-date" id="start-date" name="start-date" placeholder="YYYY-MM-DD" class ="form-control" formControlName = "startTime" data-date-format=""> To achieve the desired date ...

Modify the color of drop-down menu links

Recently, I set up a drop-down menu containing links. Initially, when hovering over the names in the menu, they would change color and display the drop-down. I had successfully made all the names golden, with the hovering name turning black while display ...

HTML/CSS - Enhances user experience by zooming in on select tag when tapped on mobile devices

I am experiencing an issue with a select menu on mobile devices. Whenever I tap on the menu, it seems to zoom in slightly. Is there a particular -webkit property causing this behavior? How can I prevent the screen from zooming when I tap on the select me ...

Prevent form submission: Attempted to stop it using `e.preventDefault()` following a `$post` function, however it resulted in

I encountered an issue with my JavaScript code $('#submit').on('click', function(e) { $('#message_line').text(""); if(validate_fields_on_submit()) { e.preventDefault(); return; ...

Vue not triggering computed property sets

As per the guidelines, I should be able to utilize computed properties as v-model in Vue by defining get/set methods. However, in my scenario, it isn't functioning as expected: export default{ template: ` <form class="add-upload&quo ...

Trigger Click event when clicking on navigation link using the ID

Currently, I am working with a WordPress theme that includes a page with 10 tabs that open individually. My approach so far has been to provide links to all tabs in the navigation bar. For instance, href="mylink.com/#tabid" It works perfectly when the p ...

The MTM test runner is failing to identify AJAX callbacks

During my manual testing, I encountered an issue where the recorded test would get stuck after a button click and not proceed to the next page, causing the test to fail. This problem also occurred in CUIT, but I was able to resolve it using Ross McNab&apos ...

refresh polymer components or make an ajax request within a custom element

I've been spending days on this issue with no success! My application relies on cookies for session handling and includes multiple custom elements imported in the header. Some of these elements need to access information from the 'cookie session& ...

Deconstructing JavaScript scripts to incorporate HTML5/CSS3 functionality for outdated browsers such as Internet Explorer

I have been researching various resources and guides related to different scripting libraries, but none of them seem to address all the inquiries I have regarding performance and functionality. With so many scripts available, it can be overwhelming to dete ...

Using the spread operator in the console.log function is successful, but encountering issues when attempting to assign or return it in a

Currently facing an issue with a spread operator that's really getting on my nerves. Despite searching extensively, I haven't found a solution yet. Whenever I utilize console.log(...val), it displays the data flawlessly without any errors. Howev ...

POST access not permitted in REST service

After creating a REST service and successfully connecting to it using JQuery ajax with JSON data, I encountered an issue specifically when trying to use the POST method. For some reason, the service is not being triggered during a POST request. The error ...

Having trouble retrieving the Rest Post response using Jquery Ajax post request

When I make a Rest call using the Ajax post method, I encounter the following error or response: {"readyState":0,"status":0,"statusText":"error"} I have enabled cors ($.support.cors = true;) and crossDomain (crossDomain: true (added in headers)). Here ...