1

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?

2 Answers 2

4

You can only call document.write while the page is still loading.

You cannot call it later, or it will blow away the existing page.

Instead, you should use jQuery's .append method.

Sign up to request clarification or add additional context in comments.

Comments

0

When you call document.write() after the DOM is ready then it actually replaces the entire page with the argument to document.write().

See DEMO.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.