Ways to insert HTML text into an external webpage's div element without using an iframe

Is it possible to generate HTML and SVG code based on the position of a Subscriber on a web page or within a specific div?

I would like to provide some JavaScript code that can be inserted inside a particular div on the page.

Using an iframe is not ideal for this situation because the height and width are not predefined and are automated.

I have been experimenting with the following code:

<html>
    <head>
        <title>TODO supply a title</title>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
    </head>
    <body>
        <div>TODO write content</div>        
        <div>

            <script>

                (function(){
                    var xhr=new XMLHttpRequest();

                    xhr.open("get","request Url of my side",true);
                    xhr.send();

                    xhr.onreadystatechange = function(){ 
                        if(xhr.readyState==4 && xhr.status==200){
                            document.write(xhr.responseText);
                        }
                    };
                }());

            </script>

        </div>   
    </body>
</html>

However, I am experiencing issues where the entire page loads before the response arrives, causing the document.write() method to erase existing content in order to display the responseText.

Any assistance on this matter would be greatly appreciated.

Answer №1

Using JQuery for the solution makes it easier compared to pure java. The response will be displayed inside the

<div id="results"></div>
.

$.ajax({
  url: "test.html",
  cache: false
})
  .done(function( html ) {
    $( "#results" ).append( html );
  });

For more information, visit: http://api.jquery.com/jquery.ajax/

Update: Pure Javascript alternative:

Async=true:

xhttp.onreadystatechange = function() {
  if (xhttp.readyState == 4 && xhttp.status == 200) {
    document.getElementById("results").innerHTML = xhttp.responseText;
  }
};
xhttp.open("GET", "test.html", true);
xhttp.send();

Async=false:

xhttp.open("GET", "test.html", false);
xhttp.send();
document.getElementById("results").innerHTML = xhttp.responseText;

For more details, check out: http://www.w3schools.com/ajax/ajax_xmlhttprequest_send.asp

Answer №2

It took me a while to locate document.scripts.

<html>
    <head>
        <title>TODO supply a title</title>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
    </head>
    <body>
        <div>TODO write content</div> 
        Here Is The Code
        <div>
        <script>
            (function(t){
                var xhr=new XMLHttpRequest();xhr.open("get","request url",true);xhr.send();
                xhr.onreadystatechange=function(){ if(xhr.readyState==4 && xhr.status==200){ 
                        document.scripts[document.scripts.length-1].parentNode.innerHTML=xhr.responseText;}}
                 }(this));
        </script>
        </div>

    </body>
</html>

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

My React application running on localhost is struggling to connect with the IPFS node

I'm currently working on a React component that allows users to submit a .jpeg file and upload it to IPFS. I've successfully started the daemon and can view the IPFS node in the IPFS-go-companion add-on with the following configurations: Gateway ...

Is there a way to eliminate the additional gap found at the bottom of a div element?

I've been encountering some difficulty when trying to insert an image into a div without any padding. The issue I'm facing is that the sizing doesn't seem to be correct; there's unnecessary extra space at the bottom. Despite my efforts ...

Sequelize does not automatically include a junction table in the associated model data

Imagine having two models, User and Event, established in a many-to-many relationship with User.belongsToMany(Event) and Event.belongsToMany(User). Everything seems to be functioning properly until executing User.findAndCountAll({include: [{model: Event}]} ...

What is the purpose of employing useMemo in the Material-UI autocomplete documentation?

My focus is on this specific demo in the autocomplete documentation. In the google maps example, there is a throttled function that is returned from a useMemo with an empty array as the second parameter. However, it raises the question of what exactly is ...

In React, the clearInterval() function does not effectively clear intervals

Currently, I am implementing the following code: startInterval = () => { this.interval = setInterval(this.intervalFunction, 10000) } stopInterval = () => { clearInterval(this.interval) } However, a problem arises when I invoke the stopInte ...

What could be causing the missing key value pairs in my JSON parsing process?

I have set up a Rails backend to serve JSON data, such as the example below from 2.json: {"id":2,"name":"Magic","location":"Cyberjaya","surprise_type":"Great","instructions":"test","status":"awesome","pricing_level":3,"longitude":"2.90873","latitude":"101 ...

TinyMCE - The control with the name 'content' is considered invalid and cannot receive focus

I am utilizing TinyMCE 4 and here is the code snippet for it: <script type="text/javascript" src="//cdn.tinymce.com/4/tinymce.min.js"></script> <script> tinymce.init({ selector: 'textarea[name=content]', ...

Is it possible to execute "green arrow" unit tests directly with Mocha in IntelliJ IDEA, even when Karma and Mocha are both installed?

My unit tests are set up using Karma and Mocha. The reason I use Karma is because some of the functionality being tested requires a web browser, even if it's just a fake headless one. However, most of my code can be run in either a browser or Node.js. ...

Improving animation performance on mobile devices using AngularJS

I've reached the final stages of developing a mobile application using AngularJS wrapped in a cordova webview. However, I'm encountering some issues with the panel transition animations. After experiencing strange behavior with ngAnimate, I deci ...

"Handsontable organizes information pulled directly from the backend database using JSON/AJAX

In order to implement the Handsontable column sorting and direction indicators, I would like to create a mechanism that sends sort requests to my database and displays the corresponding results. Although the Handsontable sort plugin is effective in allowi ...

Tips for changing a "raw" DOM Event into a React SyntheticEvent

Currently, I am working with two separate libraries. The first library emits "raw" DOM events (lib.dom.d.ts), while the other library consumes React.SyntheticEvents. I am seeking advice on the most efficient method to transform the raw event into a Synthe ...

Issues with hidden overflow and height attributes not functioning correctly in Internet Explorer 9 when using the DOCTYPE HTML standards mode

I have a <div> with overflow:hidden and height:100% that adjusts the div contents to fit the window's height on Chrome and Safari. However, in IE9, the div does not respect the styles of overflow:hidden and height:100%, causing it to expand to ...

There was no AJAX action triggered after the session was invalidated

We have a specialized JavaServer Faces web application using Primefaces 4.0 in conjunction with CAS Single Sign On integration. An issue arises when a user attempts to perform an ajax action, such as clicking a p:commandButton, after their session has bee ...

Discover the job specifications pages on Dice.Com by utilizing C programming language

I have taken on a student project involving web scraping job postings from Dice.Com for analysis. My main focus is on extracting the job description, but I am struggling to figure out how to access it. With limited knowledge in HTML and C#, I find it dif ...

Visualization of extensive datasets in JavaScript

I'm currently developing a dashboard in JS for displaying sales data plots to users. Can anyone recommend a JavaScript library that meets the following criteria: Capable of plotting a large number of points (ex: 100k or more) Interactive functional ...

Updating Angular components by consolidating multiple inputs and outputs into a unified configuration object

When I develop components, they often begin with numerous @Input and @Output properties. However, as I continue to add more properties, I find it beneficial to transition to utilizing a single config object as the input. For instance, consider a component ...

Creating a default option in a Select tag with React when iterating over elements using the map method

After learning that each element in the dropdown must be given by the Option tag when using Select, I created an array of values for the dropdown: a = ['hai','hello','what'] To optimize my code, I wrote it in the following ...

Avoiding the creation of a history entry while switching languages on a Next.js website

I'm currently developing a Next.js project that includes a language dropdown feature for users to choose their preferred language. In the existing setup, we are utilizing the router.push method from next/router to update the language selection and red ...

Is the Ajax response value consistently 1?

I am facing an issue where a JavaScript in an HTML page is sending two variables to a PHP script, which then echoes one of the variables at the end. However, the response value always remains 1. Despite trying methods like alerting, console.log, and puttin ...

Recursively toggle child elements using JQuery

My knowledge of JQuery is limited, so here's the issue I'm facing. Below is an example of the HTML structure: <ul class="first-class"> <li class="second-class"> <a href="#_"> <i class="fa fa-plus"></i& ...