jawns317
jawns317

Reputation: 1746

'Function not defined' error in script w/jQuery

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?

Upvotes: 1

Views: 1145

Answers (2)

rsp
rsp

Reputation: 111336

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.

Upvotes: 0

SLaks
SLaks

Reputation: 887433

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.

Upvotes: 4

Related Questions