Skwiggs
Skwiggs

Reputation: 1436

JavaScript function call on JQuery .load() doesn't behave like expected

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:

Upvotes: 1

Views: 116

Answers (2)

Skwiggs
Skwiggs

Reputation: 1436

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

Upvotes: 1

lshettyl
lshettyl

Reputation: 8181

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 :)

Upvotes: 2

Related Questions