Destroying the entire HTML content results in the invalidation of both the HEAD and BODY tags post-

Upon clicking a button, I execute a script that sends the entire HTML content of a webpage (everything within the <html> tags) to a CGI script for processing.

However, when I attempt to replace the existing content with the manipulated result, I encounter a problem where all <head> and <body> tags, along with their closing counterparts, are removed.

I have thoroughly checked the returned value and the original HTML content using alerts, and everything seems to be in order. But there seems to be some mysterious issue occurring after the assignment. I need assistance in figuring out what exactly is causing this problem.

Below is the JavaScript code I am using:

var originalBodyInnerHTML = document.body.innerHTML;
var htmlNode = document.getElementsByTagName('html')[0];
var post_parameters = encodeURIComponent(htmlNode.innerHTML);

makePOSTRequest("POST", "http://whatever.com/cgi-bin/doit.cgi", post_parameters, htmlNode);

function makePOSTRequest(method, url, parameters, htmlNode) {
  var http_request = getRequestObj();

  if (!http_request) {
    alert('Cannot create XMLHTTP instance');
    return false;
  }

  http_request.onreadystatechange = function() 
  {
     if (http_request.readyState < 4)
     {
        var waitingPageBody = '< img src="/img/ajaxloader.gif" alt="in progress..."/>';
        document.body.innerHTML = waitingPageBody;
     }
     else //if (http_request.readyState == 4)
     {
        if (http_request.status == 200)
        {
           alert('1response: ' + http_request.responseText);
           alert('2innerhtml: ' + document.getElementsByTagName('html')[0].innerHTML);
           document.getElementsByTagName('html')[0].innerHTML = http_request.responseText;
        }//end of if (http_request.status == 200)
        else
        {//other http statuses
           alert("There was a problem (" + http_request.statusText + ", " + http_request.status + ' error)');
           bodyNode.innerHTML = originalBodyInnerHTML;
        }
     }//end of else if http_request.readyState == 4
  }

  http_request.open(method, url, true); //async
  http_request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
  http_request.setRequestHeader("Accept", "application/atom+xml,application/xml,text/xml");
  http_request.setRequestHeader("Connection", "close");
  http_request.send(parameters);
}

function getRequestObj() {
  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
     try { 
       http_request = new ActiveXObject("Msxml2.XMLHTTP");  
     } 
     catch (e) 
     {
        try {
          http_request = new ActiveXObject("Microsoft.XMLHTTP"); 
        } 
        catch (e) {}
     }
  }

  return http_request;
}

Answer №1

I found a straightforward fix that resolved the issue for me. Here's a quick summary.

document.clear();
document.write(updatedHtml);

Replace updatedHtml with the entire HTML content of the new webpage.

Answer №2

With this code snippet,

document.getElementsByTagName('html')[0].innerHTML = http_request.responseText

You are essentially wiping out everything within the HTML document, including the body, head, and more. Perhaps you meant to do something like this instead:

document.body.innerHTML = http_request.responseText

Additionally, using jQuery can simplify and enhance your coding experience significantly.

Answer №3

Unfortunately, replacing the content of the entire HTML tag is not possible. However, you can replace the content of the body tag. The head element is unique and most browsers do not support replacing its content.

If you need to change the entire document, consider redirecting to it.

To modify specific parts of the head, try sending the changes in a different form such as JSON and use JavaScript APIs to make the necessary updates.

Answer №4

Thank you qbeuek for providing your insight!

When it comes to altering just the header, Firefox offers a workaround that looks something like this:

document.getElementsByTagName('head')[0] += "for example, some scripts"
However, Internet Explorer requires each element to be added individually to the DOM tree.

var script = document.createElement("script");
script.setAttribute('type','text/javascript');
objHead.appendChild(script); 

It's quite strange that Firefox behaves in this manner without displaying any errors...

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

Using Vuejs to implement pagination on a weekly basis

I need some help with Vue pagination. I have a ticket object, and currently, it displays in a certain way. What I'm trying to achieve is to display the tickets weekly. For example, if this week is the 31st week of the year, then from today until Sunda ...

Utilize the scope for promise .then() functions when calling a service

I've just started using AngularJS and I have a question about handling promises in controllers. In my controller, I'm calling a service that communicates with a webservice and returns a promise. I want to apply the data from the promise's s ...

Customizing File Size and Dimensions in Form Submission with Dropzone.js in JavaScript

I am currently experimenting with some sample code for Dropzone.js and am interested in finding a way to include the file size as a form field when submitting: var KTFormsDropzoneJSDemos = { init: function(e) { new Dropzone("#kt_dropzonejs_exam ...

Determining the total of input values based on identification number

Can anyone help me figure out how to calculate the total sum of the values entered using IDs? I've been struggling with it and can't seem to get it to work. Your assistance would be greatly appreciated. <input type="number" id=&quo ...

Passing large arrays of data between pages in PHP

I'm facing a challenge where I need to pass large arrays of data between pages. Here's the situation: Users input their Gmail login details in a form, which is then sent to an AJAX page for authentication and contact retrieval. If the login fail ...

What is the best way to utilize XMLHttpRequest for sending POST requests to multiple pages simultaneously?

I have a unique challenge where I need to send data to multiple PHP pages on different servers simultaneously. My logic for sending the post is ready, but now it needs to be executed across various server destinations. var bInfo = JSON.stringify(busines ...

UI not getting updated due to synchronous jQuery ajax call

I am currently facing an issue with my synchronous ajax call executed in a loop. Despite trying to update the UI before each ajax call and on the done callback method, the UI does not update until all ajax calls have been completed. Below is my code snip ...

Vercel deployment issue: Hidden input values not being detected as expected

Whenever I attempt to update the data on Vercel, an error message is displayed: invalid input syntax for type uuid: "undefined" - unable to save Oddly enough, the data updates successfully when done locally. This is how I submit the form: <form onSu ...

Show only the lower left quadrant within the img tag during the prepend operation

I'm attempting to add an <img> tag in front of a <div> similar to this example on JSFiddle. However, I have a specific requirement to only display the bottom left quarter of the image instead of the entire one. HTML Markup <div id="my ...

The remaining visible portion of a viewport is equivalent to the height of an element

Is there a way to dynamically set a div's height so that it expands from its starting position to the end of its parent div, which is 100% of the viewport minus 20 pixels? Here is an example of how you can achieve this using jQuery: $(document).read ...

Is the bearer terminology used for the authentication token or is it meant for a separate token?

In my MEVN application, I am incorporating JWT tokens and currently exploring how to transmit authentication tokens via axios. It is common practice to add "Bearer " before the token and have the server strip off "Bearer " to access the token's conten ...

Can you effectively leverage a prop interface in React Typescript by combining it with another prop?

Essentially, I am looking to create a dynamic connection between the line injectComponentProps: object and the prop interface of the injectComponent. For example, it is currently set as injectComponentProps: InjectedComponentProps, but I want this associat ...

Issue with modal rendering in Bootstrap4 when the body is zoomed in

I am encountering an issue with a Bootstrap html page where the body is zoomed in at 90%. The Bootstrap modal is displaying extra spaces on the right and bottom. To showcase this problem, I have created a simple html page with the modal and body set to 90% ...

What are the best practices for protecting a web application with login and database in the year 2022?

My knowledge of security is outdated and I am looking to update my skills in full stack development. Currently, I am exploring Oauth2, JWT, Next.JS, Auth0, and more, but I am struggling to integrate all these components together. Please bear with me as I m ...

I am looking to sort through the data based on the courseCode, but I can't seem to find a way to do it

Here is the JSON data after converting it with res.json() I attempted to filter it based on course code, let's say the code is: 301. I am confused about how to achieve this using JavaScript because of the nested structure. Here is the code snippet I ...

Encountered an issue while attempting to integrate Nebular into my Angular application

As a newcomer to Angular, I decided to try installing Nebular using the command ng add @nebular/theme. However, I encountered an error in the process. Upon entering the command into my terminal, the following error message appeared: ? Which Nebular theme ...

Error: Unable to access property 'nTr' as it is not defined

When I invoke the fnSelect function, an error occurs in Chrome: Uncaught TypeError: Cannot read property 'nTr' of undefined This is the code snippet causing the issue: $('#ToolTables_table_id_0, #ToolTables_table_id_1').mousedown(fun ...

The navigation bar fails to respond when clicked on mobile devices

Calling all developers! I need a helping hand to tackle an issue that's holding me back from completing this website. Can someone please take a look at on their smartphone browser and figure out why the responsive menu icon isn't working when cl ...

Is it possible for me to use the name "Date" for my component and still be able to access the built-in "new Date()" functionality?

Currently following the NextJS tutorial, but adding my own twist. In the NextJS example, the custom component is named "Date" (/components/date.js) and does not utilize the built-in Date() object in processing, making it unique to the file. In my scenario ...

Tips for presenting JSON date in JavaScript using Google Chart

I am in urgent need of assistance with this issue. I am trying to display the date from PHP JSON data retrieved from my database in a Google Chart using JavaScript. Below is the PHP code snippet: $data_points = array(); while($row = mysqli_fetch_array($r ...