skip to Main Content

Loading JS file with HTML content to a div via ajax, if I load it multiple times the JS functions inside the test.js file runs multiple times like the content is loaded.

Creating the HTML content with PHP:

$html = '
    <script src="js/test.js" charset="utf-8"></script>
    <div id="form-container" class="p-3">
       <label>Teszt</label>

        <select class="form-control" id="type" name="type">
            <option value="t1">type 1</option>
            <option value="t2">type 2</option>
        </select>

    </div>
';

After the content is created, it sends back to the ajax and adds the content to the div.

Inside the test.js file there is event handlers like:

$(document).on("change", '#type', function (event) {
   alert("test");
});

I tried to add a .js file version with PHP DateTime, but it’s not working.

2

Answers


  1. Chosen as BEST ANSWER

    Found the solution, with the multiple ajax load it delegate the event handlers multiple times.

    To avoid it, need to remove the event handler before delegate it again.

    $(document).off("change", '#type');
    
    $(document).on("change", '#type', function (event) {
       alert("test");
    });
    

  2. You could do something like below:

    <?php
    
    $timestamp = time();
    
    $html = "
        <script src='js/test.js?ver={$timestamp}' charset='utf-8'></script>
        <div id='form-container' class='p-3'>
           <label>Teszt</label>
        </div>
    ";
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search