Bakhtiyor
Bakhtiyor

Reputation: 7318

Including file from PHP inside dialogbox of jQuery is misleading javascript

I have 3 files (file1.php, file2.php and file3.php). Their contents are given below. When I load file1.php it shows two times the message of "Hello" in an alert box. But when I include file3.php before or after dialogbox (which is in file2.php) then it shows that message only one times (which is what I want).

Does anybody know where is the problem please?

Thanks.

The content of file1.php

<?php 
     some operations
     require_once("file2.php");
?>

The content of file2.php

<script type="text/javascript">
   $(document).ready(function() {
       var dialogOpts={        
         autoOpen: true,
         modal: false,
         height: "auto",
         resizable: false,
         closeOnEscape: true,
         width: 700,
         position: ["center",30]
       }
       $('#learning_activity_wizard_dialog').dialog(dialogOpts);
   });
</script>
<?php 
     some operations         
?>
<div id="learning_activity_wizard_dialog" title="Learning Activity Wizard" class="dialogbox">
    some content
    <?php require_once("file3.php"); ?>
</div> 

The content of file3.php

<script type="text/javascript">
  $(function () {
      alert('Hello');
  });
</script>
sometext

Upvotes: 2

Views: 833

Answers (3)

Boopathi Rajaa
Boopathi Rajaa

Reputation: 4729

http://jsfiddle.net/uRhQT/

i guess this is your problem, adding script tag inside a html that will load again using jquery.

The solution to this what you have only ... use the script outside the div.

Reason: The script tag content is executed when defined inline. So When your dialogbox is shown, the contents are copied to the dialogbox which makes it new inline script. So it gets executed and another alert box is shown.

Upvotes: 2

Naftali
Naftali

Reputation: 146360

When you do $('#learning_activity_wizard_dialog').dialog(dialogOpts); it will run the script again.

If you do not want this to happen, move that script tag out of the div that will later become a dialog.

Upvotes: 3

Mike Ruhlin
Mike Ruhlin

Reputation: 3556

When jQuery creates the dialog box, it copies everything in the learning_activity_wisard_dialog div to a new DOM node, including the script tag.

So, the tag runs once when the page loads, then again when the dialog is rendered. Move your script out of that div, or just use some bool to track whether it's already run or not.

Upvotes: 3

Related Questions