0

I have 2 javascript files included in a popup (simple div) generated using ajax.

<script type="text/javascript" src="<?php echo JS ?>pm.js"></script>
<script type="text/javascript" src="<?php echo JS ?>chat.js"></script>

When you close the popup and re-open it, the jQuery bound functions in the two files execute twice.

for example

//connection
    $(document).bind('connect', function() {
            var conn = new Strophe.Connection('my-http-binding-url');
             conn.connect(inbox.data.jid, inbox.data.pass, function(status){
            inbox.connection = conn;
             alert(status)
            });
});

First time I open the popup, it displays the alert message : 5, which means it connected successfully.

But when I close the popup, and re-open it, it shows me the message twice... I assume the code is executed twice because it's not unloaded.

4
  • you can't unload javascript. Once it is executed, it's effects on the dom won't go away by simply removing the javascript. Commented Oct 8, 2013 at 15:12
  • I know I must break the function by another affectation like var connect=function(){} or something like that But here I have a bound function, how can I achieve that? Commented Oct 8, 2013 at 15:12
  • 2
    unbind it with the .unbind method. Commented Oct 8, 2013 at 15:13
  • api.jquery.com/unbind Commented Oct 8, 2013 at 15:13

1 Answer 1

2

You can achieve by following two different way

  1. Open your popup within a Iframe and destroy Iframe on closing the popup
  2. If you are not using Iframe, then move those script tag from "popup" template and keep them within "head" or just above closing body tag.

Note: You can not remove javascript once it loaded. Use "Firebug" or "Chrome Developer Tool" 's Network tab and make sure that javascript is not loaded multiple time.

Edit: You can access the dynamic HTML after ajax completed

$.ajax({
   ...,
   ...,
   success: function afterAjax(){
      // Insert dynamic HTML in Document
      // Any jQuery selector/function you can use here
    }
}
Sign up to request clarification or add additional context in comments.

5 Comments

Thank you so much, I want to use the second way, but .. I can't access jQuery DOM elements in the Ajax result from outside... that's why I included them in the ajax Result.
@SmootQ Why? You can do, see my edit. If I am wrong, explain your problem bit more
ok, move the function outside of the call and give it a name. that way you can reach it from anywhere and easily unbind it.
Hilarudeens, The 2 one seems working, anyway I must find out why the result DOM is not recognized outside the ajax result div. Thanx again ;) +1 best answer
Yeah, Dandvis, I agree +1 :)

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.