Using JavaScript's Document.Write with AJAX will overwrite the entire body content

I am currently working on implementing a basic ajax call that fetches the content of a specific url and inserts it into the page. However, I am encountering an issue where it replaces the entire body content with this retrieved information.

Below is the JavaScript code:

(function(){
    var mb = window.mb = {};

    function get_ad(url, parameters){
        var result = "";
        var http_request = false;

        if (window.XMLHttpRequest) { // Mozilla, Safari,...
            http_request = new XMLHttpRequest();
            if (http_request.overrideMimeType) {
                http_request.overrideMimeType('text/html');
            }
        } else if (window.ActiveXObject) { // IE
            var avers = ["Microsoft.XmlHttp", "MSXML2.XmlHttp", "MSXML2.XmlHttp.3.0", "MSXML2.XmlHttp.4.0", "MSXML2.XmlHttp.5.0"];
            for (var i = avers.length -1; i >= 0; i--) {
                try {
                    http_request = new ActiveXObject(avers[i]);
                    if (http_request){
                        break;  
                    }
                } catch(e) {}
            }
        }
        if (!http_request) {
            alert('Cannot create XMLHTTP instance');
            return false;
        }

        http_request.onreadystatechange = function(){
                                              if (http_request.readyState == 4) {
                                                 if (http_request.status == 200) {
                                                    gen_output(http_request.responseText);
                                                 } else {
                                                    alert('Error');
                                                 }
                                              }
                                           }

        http_request.open('GET', url + parameters, true);
        http_request.send(null);
    }

    function gen_output(ad_content){
        document.write("<div id=\"mb_ad\">");
        document.write(ad_content);
        document.write("</div>");
    }

    get_ad("http://localhost/test/test.html", "");
})();

and here is the 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=utf-8" />
<title>Untitled Document</title>
</head>

<body>
    i am text before <br/>
    <script type="text/javascript" src="mb.js"></script>
    <br />
    i am text after 
</body>
</html>

Upon using firebug to inspect, only the <div id="mb_ad"> and content from the test.html page are visible. The text before and after do not display. If I eliminate the ajax call and simply use three document.writes, then the text before and after show up correctly. Keep in mind that jQuery is not an option, as I need to accomplish this without relying on a large library due to size and speed considerations.

Answer №1

Avoid using document.write after the document has finished loading to prevent opening a new document that replaces the current one.

Instead, utilize the innerHTML property to insert HTML code into an element:

function display_ad(ad_content){
  document.getElementById('mb_ad').innerHTML = ad_content;
}

Ensure the element is placed before the script so it exists when the callback function is triggered:

i am text before
<div id="mb_ad"></div>
i am text after
<script type="text/javascript" src="mb.js"></script>

The placement of the script doesn't impact the outcome since nothing will be written to the document in that location.

Answer №2

If you find yourself unable to control the remote script, there may be a way to implement a workaround like this:

<script>
var tmp = document.write;

document.write = function () {
  document.getElementById('someId').innerHTML = [].concat.apply([], arguments).join('');
};
</script>
<script .....>
document.write = tmp;

Although it's not the most elegant solution, this hack appears to do the trick...

Answer №3

const newDiv = document.createElement('div');
newDiv.id = 'custom_ad';
newDiv.innerHTML = ad_data;

You are now free to place this element in any location on your webpage.

Answer №4

If you want to dynamically add HTML code to a webpage, one way to do it is by using the following script:

<script>document.body.innerHTML+="//Insert Your HTML Code Here";</script>

Answer №5

Similar solution by Leon Fedotov but with added jQuery elements

{
  var previous_document_write = document.write;

  var $zone = $('.zone.zone_' + name);
  // redefining document.write within this function
  document.write = function () {
    $zone.append([].concat.apply([], arguments).join(''));
  };
  // OA_output[name] might contain unsafe document.write calls
  $zone.html(OA_output[name]);

  document.write = previous_document_write;
}

Answer №6

Encountered a similar issue with this code snippet:

$content[] = '<script>
           if($("#mf_dialogs").length == 0) {
               document.write("<div id=\"mf_dialogs\"></div>");
           }
           </script>';

Consider using this alternative code for better efficiency:

$content = '<div id="dialogContainer"></div>
         <script>
              if($("#mf_dialogs").length == 0) {
                  document.getElementById("dialogContainer").innerHTML="<div id=\"mf_dialogs\"></div>";
              }
         </script>';

Answer №7

A method to mimic the behavior of document.write involves the use of the following code snippet:

<script>
  (function(script) {
    var parent = script.parentNode;
    var node = document.createTextNode('Unexpected!');
    parent.replaceChild(node, script);
  })(document.currentScript);
</script>

With this approach, you can insert any HTML content instead of a script element. For simpler scenarios where you can wrap a script within another tag, an even more straightforward version can be utilized.

<script>
  document.currentScript.parentElement.innerHTML = 'Unexpected!';
</script>

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

What is the best way to store and serve the AngularJS library locally in a static manner?

I have a project in Angular that needs to be developed without an internet connection, which means the CDN links will not work. I want to save the AngularJS library to a directory within my project. This is what I attempted: First, I visited the CDN link, ...

Trigger functions when the window is scrolled, resized, or when the document is fully loaded

I have a few functions that need to be executed under specific conditions: window.scroll window.resize document.ready For example: <script> function myFunction1(data){ /*code*/ } function myFunction2(data){ /*code*/ } ...

Is it possible to perform direct URL searches using react-router-dom?

Encountering an issue when attempting to directly copy a route, resulting in the following error: Error: Cannot Access / home Despite utilizing various methods such as browserHistory, I am unable to successfully render views when navigating with menu i ...

JS/Docker - The attribute 'user' is not recognized in the context of 'Session & Partial<SessionData>'

I'm attempting to integrate express-session into my Node.js application running within Docker. I've come across several discussions on the topic: Express Session: Property 'signin' does not exist on type 'Session & Partial<Se ...

Having trouble retrieving responseText from an AJAX request using Laravel

I am facing an issue with my AJAX call setup. Here is how it looks: function getPosts(){ $.ajaxSetup({ headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') } }); $.po ...

Displaying database records in custom fragments using Spring Boot and Thymeleaf

I'm struggling with displaying database records on a webpage in a specific format. To achieve this, I've created a thymeleaf fragment to act as a template for each record in my database. However, I can't figure out how to make these fragment ...

Vue.js - Error: Module not found: Cannot locate module 'lottie-vuejs'

I've been attempting to integrate lottie-vuejs into my project. After running the npm install command and following the steps outlined here, I encountered an issue. Unfortunately, I received the following error message: Module not found: Error: Can ...

Choose the div without a class

I currently have several divs displayed on my website. <div class="slide bx-clone"></div> <div class="slide"></div> <div class="slide"></div> <div class="slide bx-clone"></div> <div class="slide bx-clone" ...

Issue with scrollTop not functioning when using onclick on an <a> tag within a div

After various attempts and research online, I am still experiencing erratic scrolling behavior with the scrollTop function. My goal is to scroll within a specific div when clicking on links. The content of my div: <div id="test" style="height:400px; o ...

The CheckboxTable component in material UI fails to update when there is a change in props

As I develop an admin system, one of the key features I want to implement is the ability to display a list of users in a table format. Additionally, I want to enable bulk actions such as delete and update flags, along with pagination. <CheckboxTable ...

When attempting to pass Rgraph image data through a jQuery AJAX call, a 403 Forbidden error is being

I have been working on a project that involves creating graphs/charts using the Rgraph PHP library. To generate these charts, my script follows these steps: Calculate the graph points and render the graph using the Rgraph Draw() method. Create an image d ...

Looking to showcase Unicode characters with jQuery AJAX - here's how!

I am currently working on retrieving unicode characters from a MySQL server using PHP, Ajax, and jQuery in the code snippet below. $.post("test.php",{tableName: A_table}, function(data) { $.each($(data), function(key, value) { ...

Performing a database query with jQuery AJAX

My AJAX function looks like this: function admin_check_fn(type) { //$("#notice_div").show(); //var allform = $('form#all').serialize(); $.ajax({ type: "POST", //async: false, url: "<?php bloginfo('t ...

When a label tag is used to surround a radio button, it will hinder the radio button's ability to trigger a "change" event listener in JavaScript

Issue I'm facing an issue with dynamically generated HTML via JavaScript, which includes a form with radio buttons. I have attached event listeners to the radio buttons that call a function when their value changes. However, I noticed that the "chang ...

I discovered that the chips' content was in need of updating once I selected the content from the menu

I want to create a chips feature similar to Google Flights where clicking on the chips opens a menu. Currently, when I click on the chips, the menu opens up and 'Sports' is displayed as a chip. However, I want to update the 'Sports' tex ...

Unable to integrate bootstrap with webpack

Incorporating Express, Webpack, and Bootstrap. Currently utilizing css-loader for my stylesheets. Below is the contents of my webpack.config.js: const path = require("path"); config = { "entry": "./modules/entry.js", "output": { "path": p ...

Tips for utilizing the 'contains' feature within web elements with Java Selenium WebDriver?

In my current project, I am facing a challenge with two specific elements: one is a string formatted as ABC £12,56 and the other is a box called "Cashbox" that should be 15% of the value of the string. However, when attempting to locate the CSS for both e ...

Create a NodeJS script that sends a socket message upon receiving parameters from a URL

My goal is to establish a socket connection using socket.io when the get request ?server is detected in the URL. The buttons on the page are dynamically loaded from a JSON file that is sent by the Node.js server. Although I am sending the socket upon rece ...

The handleSumbit feature seems to be malfunctioning in a React Native application that utilizes React-Hook-Form in combination with yup

Greetings, I am currently utilizing React-hook-form and yup for validation in my React Native project. However, I have run into an issue with the handleSubmit function not functioning properly in my ResetPasswordScreen component. Strangely enough, a simila ...

To retrieve the value of an element in the Response tab of the Network tab in Google Chrome's developer tools, I am looking to use JavaScript, TypeScript, or Cypress

Currently working on a cypress test case where I am struggling to fetch the requirement id value from results using JS/TS/Cypress. Unfortunately, I haven't been able to find a solution yet. I've come across various posts and articles, but none o ...