1

I am working on a website for school, and am currently implement some sort of admin dashboard. For that, I decided to dynamically load 'modules' (actually simply .php files) into a div designed to hold them.

This works fine for modules that don't depend on specific js files, but there's one that needs the 'participation.js' file.

I had tested the module in a whole window where there was an 'onload="initSelectable()"' on the body directive, but calling this function when the module is loaded in the admin dashboard doesn't do anything.

Here is the content of participation.js (it is simply copy/pasted from the JQuery selectable, and I slightly modified the behaviour):

var selectedPlayerIDs = [];

function initSelectable(){
    $('#selectable').selectable();
    $('#submitParticipationBtn').hide();
    console.log("initSelectable");

    $("#selectable").selectable({
        stop: function() {
            var count = 8;
            var result = $("#selectedPlayersCount").empty();
            $(".ui-selected", this).each(function() {
                count--;
                selectedPlayerIDs.push($(this).attr("data-playerid"));
            });
            if(count > 1)
                $('#selectedPlayersCount').html(count + " more players");
            else if(count === 1)
                $('#selectedPlayersCount').html(count + " more player");
            else if(count === 0)
                $('#selectedPlayersCount').html("no more player. You're good to go !");
            else if(count === -1)
                $('#selectedPlayersCount').html(-count + " player less");
            else
                $('#selectedPlayersCount').html(-count + " players less");
            if(count === 0)
                $('#submitParticipationBtn').show();
            else
                $('#submitParticipationBtn').hide();
        }
    });
}

function submitParticipation(){
    alert( "JS loaded" );
    $.post("participation.php", {selectedIDs : JSON.stringify(selectedPlayerIDs)}, function() {

    })
    .onSuccess(function() {
        alert( "onSuccess" );
    })
    .fail(function() {
        alert( "error" );
    });
}

So basically this code initializes the JQuery Selectable environment. When loading the module in the div, I use $('#dynamicPage').hide().load("module1.php").fadeIn('500'); directly followed by $.getScript("participation.js");

The thing is, the module correctly loads (at least the HTML part), and I can see in the console log ("initSelectable"). But I need to manually re-execute initSelectable() from the command for it to be effective. And when I do that, I see there's an undefined getting logged in the console, before the second ("initSelectable") log (this might be due to the fact that I'm trying to call $('#selectable').selectable(); a second time).

For example, here is the participation module .php file:

<div class="well">
    <h3>Create a participation</h3>
    <h4>Please select <span id="selectedPlayersCount">8 players</span></h4>
    <div class="row">
        <div class="col-sm-4">
            <ol id="selectable">
                <?php include_once "../Ctrl/rankingList.php" ?>
            </ol>
            <button class="btn btn-success" id="submitParticipationBtn" onclick="submitParticipation()">Submit</button>
        </div>
    </div>
</div>

I've tried countless different way to call the initSelectable function (callbacks, events, timeOuts, etc...) and no matter what, even if it gets executed by the browser, I still need to manually re-execute it for it to be working...

So basically, my question is:

  • What is the correct way to load HTML and dependant JS files into a div ?
5
  • This type of "modules" organisation is a typical case where a dependency injector might help... I let you google that :-) That said, although it doesn't show in your code, it seems you're using inline event binding (e.g: onload attribute in HTML). This is a bad practice and you should only werite your javascript inside dependant JS files instead. Commented Jun 8, 2015 at 11:38
  • Unrelated, .onSuccess(function() { must be .done(function() { Commented Jun 8, 2015 at 11:40
  • It'd be useful to see the HTML the .load injects into the div. Go ahead and post that as well. Commented Jun 8, 2015 at 11:42
  • @Bartdude I have tried onload etc but those don't work at all, you can check the example .php file I'm trying to inject (updated my question). Commented Jun 8, 2015 at 11:49
  • @LShetty Oops yes indeed I need to change that to .done(); Also, I updated my question with an example of file to inject :) Commented Jun 8, 2015 at 11:50

2 Answers 2

2

What is the correct way to load HTML and dependant JS files into a div ?

So, this would be a good start and you can take it from here.

$(function() {

    $("#myDiv").load("myfile.php", function() {

        console.log("HTML has been injected!");
        //Get dependencies
        $.getScript( "myscript.js" )
        .done(function( script, textStatus ) {
            //Call methods from within myscript.js
            initSelectable();
        })
        .fail(function( jqxhr, settings, exception ) {
            console.log("There was an error!");
        });
    });

    // Remove inline event handler and bind it like below.
    $("#myDiv").on("click", "#submitParticipationBtn", submitParticipation);

    function submitParticipation() {
        //...
        //...
    }
});

I am not sure why $('#selectable').selectable() is being duplicated. But, it's left you to fix :)

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

Comments

1

Okay so I was doing it wrong. I thought that putting the <script src "path/to/script.js"></script> in the module file didn't work. But actually, it does, and I simply needed to call $(document).ready(initSelectable()) in the JS file to be sure the initSelectable was executed at the right time.

So now my .php file looks like this:

<div class="well">
    <h3>Create a participation</h3>
    <h4>Please select <span id="selectedPlayersCount">8 players</span></h4>
    <div class="row">
        <div class="col-sm-4">
            <ol id="selectable">
                <?php include_once "../Ctrl/rankingList.php" ?>
            </ol>
            <button class="btn btn-success" id="submitParticipationBtn" onclick="submitParticipation()">Submit</button>
        </div>
    </div>
    <script src="../Ctrl/participation.js"></script>
</div>

Thanks all for your help :P

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.