John Wooten John Wooten - 5 months ago 31
Ajax Question

How to get HTML written to a new tab using window.document.write to render?

I have a javascript program that submits a form to a PHP page that collects data depending upon the form entries. I have verified that the data is returned correctly. In the following piece of the code, the success portion of the ajax call is shown:

success: function(msg){
var newWindow ="_blank");
var result = $.parseJSON(msg);
var array =;
newWindow.document.write("<!DOCTYPE html><html><head></head><body>");
for( var i=0; i<result.entries.length; i++ ) {
var obj = result.entries[i];
alert( "Printout complete" );

The tab is opened, and the
elements, which are strings, are written to the new tab. This is what is displayed on the browser window:

<h1>Age 1</h1><h2>Test</h2><br/>Test

The page source shows:


The PHP page which filled the result obj contained:
if( $age != $last_age ) {
$last_age = $age;
array_push($items,"<h1>Age $age</h1>");
if( $age == $last_age && $event != $last_event ) {
$last_event = $event;

$result["entries"] = $items;
header("Content-type: application/json");
header("Cache-Control: no-cache, must-revalidate");

echo json_encode($result);

It appears that putting the h1 etc. into the strings to be returned result in them being encoded as <h1> etc. They then show up in the source code for the page as '<', but the entire lines containing the
is enclosed in double quotes. If where I write
, I substitute "<h1>Hello World</h1>", I get that rendered on the page.

How do I get the HTML to the page and have it rendered with the h1, h2, etc.?

Answer Source

Well, it was going around my elbow to get from my finger to my thumb, BUT, I got it to work. In the PHP I changed to store a JSON array as each element in items, viz.

   $nameAttr = 'h1';
   $item = array();
   $item[$nameAttr] = "Age $age";

similarly for h2 element and straight text element.

In the index.html page where it is processed I replaced the newWindow.document.write(obj), with:

               var objJSON = result.entries[i];
               $.each(objJSON, function(key, value) {
                if( key == 'h1' ) {
                } else if (key == 'h2' ) {
                } else {

It rendered as I wished! This seems inordinately complex to do such a simple thing as one might have many types of entries on the page such as <tr>, etc. This method would require 'keys' for each html element and a subsequent handler for that key. If anyone has a clue how to include the html tags in the PHP code, it would be helpful!

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download