Kehran
Kehran

Reputation: 83

JQuery code stops working after refresh

I'm currently having some issues with a php game I'm creating. Everything works exactly the way I need it to until I refresh the page, then things start to get a bit strange. I've included some of my code below.

my main JS script "Main.js"

$(document).ready(function(){

//match boxheight
$('.box').matchHeight();

var state; //Variable to detect what "page" we are on. defaults to homepage or index.php

function CheckSwitch()
{   
    switch(state)
    {
        case "HomePage":
            console.log("test");
        break;

        case "My Computer":
        //($table,$col)
        console.log("state active");
            $.post("Data.php",{function_: "GetData",table:"virtualpc",col: "ip",},
            function(data){$("#V_IP").text(data); console.log("My V_IP is: " +data);});         
            $.post("Data.php",{function_: "GetData",table:"virtualpc",col: "password",},
            function(data){$("#V_Pass").text(data);});              
        break;

    }
}   

//Sign In Button Code
$("#SignInB").click(function()
{
    var _password = $("#PasswordL").val();
    var email = $("#EmailL").val()
    if(email != "" && _password != "")
    {
                $.post("Login.php",
                {
                    function_: "Login",
                    Lpass: _password,
                    Lemail: email
                },
                function(data){
                    if(data != 0)
                    {                   
                    $("#NewUserNav").hide(500);
                    $("#UserNavigation").show(1000);
                    $("#WelcomeMessage").hide(1000);
                    uid = data;
                    console.log("User ID: " +uid);
                    }
                    else
                    {
                        {$("#message").text("Incorrect login information!"); $("#message").css("color","white");}
                    }

                });     
    }   
    else{$("#message").text("All fields required!"); $("#message").css("color","white");}

            $.post("CheckSession.php",
                {
                    function_: "SessionStat",
                },
                function(data){
                    state = data;
                    console.log("Current State: " + state);
                    CheckSwitch();
                });         

}); 
//End Sign In  Button code

});

This is where I detect the button click for "SignInB" and send the Ajax request. The ajax request is sent to my Data.php page (the last code block here) and a response is echoed. Now this works PERFECTLY fine. the only issue is that when i refresh, the jquery code in the switch (under case: "my computer") doesn't execute.

My html fie "CMD.html"

<div id = "CMD">

    <span class="type-itCMD">
    <h1 style = "text-align:center">My Computer</h1>

    <h4 class="MyPCHeaders">My Information</h4>
        <p class = "MyPCInfo">Virtual IP : </p><span class = "MyPCInfoText" id = "V_IP">xxxxx</span>
        <p class = "MyPCInfo">Virtual Password : </p><span class = "MyPCInfoText" id = "V_Pass"></span>

    </span>
</div>

My Ajax file to get data from DB and send it back

 <?php
session_start();
include("functions.php");


if(isset($_POST['function_']) == "GetData")
{
    $table = $_POST['table'];
    $col = $_POST['col'];
    GetData($table,$col);

}   
function GetData($table,$col)
{
    $id = $_SESSION['uid'];
    $conn = connect();
    $CheckData = mysqli_query($conn, "SELECT * FROM `{$table}` WHERE user_id = '$id' ") or die(mysqli_error($conn));
    if(mysqli_num_rows($CheckData) == 1) //We found Data row!
        {
            $DataValue = mysqli_fetch_assoc($CheckData);
            $MyValue = $DataValue[$col];
            echo $MyValue;
        }
}


?>

So again, when the SignIn button is clicked, the Ajax request is sent and a response is received! The jquery in the "my computer" case does work afterwards! It's only once i refresh and try to call the switch statement again (outside of clicking the SignIn button) does the jquery code not work. I can't seem to figure this one out and would really love some help or advice!

Edit: I have tried $(window).load(function() {}); with no luck. Maybe I'm using it wrong?

EDIT EDIT: I've managed to make the state variable persist with $_Session and an Ajax request. I just simply call this request and get the state session every page load.

                $.post("CheckSession.php",
                {
                    function_: "SessionStat",
                },
                function(data){
                    state = data;
                    console.log("Current State No Button: " + state);
                    CheckSwitch();
                });

I then run the CheckSwitch() function again to check the switch and run the Jquery commands... Now something very odd happens. The jquery commands wont update the html after the refresh. The jquery will however console log the correct data...just not display it in the span? What am I missing? Do the spans not refresh with the new data content when i refresh the page?

Upvotes: 1

Views: 997

Answers (2)

Kehran
Kehran

Reputation: 83

Thank you everyone for the help! I managed to get my state variable to persist and ended up having to use the setTimeOut event. I figured out that my ajax requests were sending and received all of the correct data, the problem was within my jquery!

I translated the jquery to regular JS and the console spit out an error about not being able to access the innerHTML of 'x' element. My jquery code was trying to access the element before it was created but jquery wouldn't produce an error.

I simply added a setTimeOut event during my CheckSwitch() function call and boom, although a bit delayed it works!

EDIT: after more research the cause of all my trouble was a typography plugin I was using! (facepalm). I was actually writing everything out in the html letter by letter which would only create the elements AFTER they were fully typed out. The setTimeOut event just gave the plugin enough time to type it all out. I've now fixed everything so the two aren't dependent anymore. :)

Upvotes: 0

ADyson
ADyson

Reputation: 61784

The value of "state" only exists as long as the page does. When you reload the page, the previous copy of the page is destroyed, and a new copy downloaded from the server (or, possibly, retrieved from the cache). Everything gets reset to its initial values, as if the previous version of the page never existed. This is by design - the web is intrinsically "stateless" (oh, the irony).

If you want the value of "state" to be maintained between page loads, you need to persist it somehow. One obvious and straightforward way would be to maintain the value in $_SESSION on the server, and use PHP to inject its current value into the JavaScript, to be used when the page loads.

Upvotes: 1

Related Questions