I’m getting a “function not defined” Javascript error with the following code, which uses jQuery:
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.0/jquery.min.js"></script>
<script type="text/javascript">
function log_in() {
document.write('Logging in ... ');
$.post('process_ajax.php', { 'action' : 'log in' }, function(data) {
document.write(data);
create_new_story();
});
}
function create_new_story() {
document.write('Creating new story ... ');
$.post('process_ajax.php', { 'action' : 'create story' }, function(data) {
document.write(data);
});
}
</script>
</head>
<body onload="log_in()">
Processing...<br>
</body>
</html>
Here’s the PHP script it’s calling (for testing purposes):
<?
die("Page opened.<br>");
?>
The first function called — log_in() — works fine, but I get this error:
“Error: create_new_story is not defined”
And that function never gets executed.
I’m sure I’m missing something simple. Can I get a new pair of eyes to find it?
You can only call
document.writewhile the page is still loading.You cannot call it later, or it will blow away the existing page.
Instead, you should use jQuery’s
.appendmethod.