I have a PHP script which I want to output some text which I’m calling with AJAX to place in a textbox. The text is generated with JavaScript but if I call document.write() then the whole page is refreshed and the text is displayed on its own – not in the textbox.
Here is the backend script:
<?php
// unrelated stuff
?>
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1" />
<meta name="robots" content="NOINDEX, NOFOLLOW" />
<!-- JQuery -->
<script type="text/javascript" src="<?php echo $toolsDirectory; ?>/jquery-1.4.3.min.js"></script>
<?php if ($a = 2) { ?>
<script src="someScript.js" type="text/javascript"></script>
<script type="text/javascript">
<!--
var a = new A;
document.write(a.go("<?php echo $testString; ?>"1));
// -->
</script>
<?php } ?>
</head>
<body>
</body>
</html>
I’m calling it with $("#output").load("script.php");.
I have also tried $(body).html() with the same result.
So just to sum up – the Javascript works, it outputs the right stuff. If I just echo "hello" in the PHP, it loads it into the textbox as expected – it’s just the Javascript writing that is confusing me.
A document can be in two states — open and closed.
While loading a document, it is open. Once it has finished loading, it is closed.
If you reopen a document, it wipes out everything in it.
If you try to write to a document, and it is in a closed state, then it automatically opens it.
This is what is happening to you.
Forget about
document.writeand use DOM methods to modify the document instead.