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 = window.open("_blank");
var result = $.parseJSON(msg);
var array =
newWindow.document.open();
newWindow.document.write("<!DOCTYPE html><html><head></head><body>");
for( var i=0; i<result.entries.length; i++ ) {
var obj = result.entries[i];
newWindow.document.write(unescape(obj));
}
newWindow.document.write("</body></html>");
newWindow.document.close();
newWindow.focus();
alert( "Printout complete" );
}
entries[i]
<h1>Age 1</h1><h2>Test</h2><br/>Test
<html><head></head><body>"<h1>Age</h1><h2>Test</h2><br/>Test"</body></html>
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;
array_push($items,"<h2>$event</h2>");
}
array_push($items,"<br/>$data");
}
$result["entries"] = $items;
header("Content-type: application/json");
header("Cache-Control: no-cache, must-revalidate");
echo json_encode($result);
entries[i]
unescape(obj)
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";
array_push($items,$item);
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' ) {
newWindow.document.write("<center><h1>"+value+"</h1></center>");
} else if (key == 'h2' ) {
newWindow.document.write("<center><h2>"+value+"</h2></center><br/>");
} else {
newWindow.document.write(value);
}
});
}
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!