-2

I have a problem with js script.

I load subpage by ajax and append code to div.

$.ajax ({           
    type: "POST",
    url: "load/page/",
    dataType: "json",
    success : function(data) {
        $('.content').empty();
        $('.content').append(data);             
    },
    error : function(e) {
        console.log(e);             
    }           
});

Subpage contains appeal to js script:

<script src="//<?php echo $_SERVER['SERVER_NAME'].'/'.BASE_DIR; ?>/scripts/settings.js"></script>

Why when i execute ajax multiple times settings.js events are executing multiple too? I want to could execute ajax code multiple times but js scripts are executing only once.

9
  • why don't you put the code you have in settings.js in a function, which you load directly in the current page. Then you can call the function from your success handler. Commented Jun 4, 2017 at 21:19
  • because i have a lot of subpages and a lot of js scripts and I want to load only one script assigned to a subpage. Commented Jun 4, 2017 at 21:23
  • I cannot reproduce the behaviour you describe: the script is executed every time it is appended. Commented Jun 4, 2017 at 21:38
  • In settings.js I have an event: $(document).on("click", "#update-button", function() { alert('click'); }); And after multiple execution ajax and click button i getting a lot of alerts Commented Jun 4, 2017 at 21:58
  • That's going to turn into a real mess, but you can try removing document event handlers with .off() after you call .empty(). Another option would be to add a big if block around the code in the scripts and check if you've loaded it already (if they're all doing the same kind of $(document)-like stuff). Commented Jun 4, 2017 at 22:22

1 Answer 1

0

I replaced $(document) to $('.content') and add line $('.content').off(), now code is working great.

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

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.