-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.

polak polkovski
  • 97
  • 1
  • 10
  • 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. – trincot Jun 04 '17 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. – polak polkovski Jun 04 '17 at 21:23
  • I cannot reproduce the behaviour you describe: the script is executed every time it is appended. – trincot Jun 04 '17 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 – polak polkovski Jun 04 '17 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). – Jared Farrish Jun 04 '17 at 22:22
  • What's suggested here (for use in your event handler definitions) might be perfect, since you'd do it at the spot you're handling it: https://stackoverflow.com/a/825193/451969 I would suggest unique event name aliases though (like `click.update_stuff`). – Jared Farrish Jun 04 '17 at 22:25
  • Thanks for advices. I replaced $(document) to $('.content') and add line $('.content').off(), now code is working great. – polak polkovski Jun 04 '17 at 22:30
  • Nice, document that as an answer and mark it accepted (when it's ready). – Jared Farrish Jun 04 '17 at 22:30
  • The question does not have the information that was apparently the source of the problem. – trincot Jun 05 '17 at 06:06

1 Answers1

0

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

polak polkovski
  • 97
  • 1
  • 10