Arraying Arraying - 21 days ago 5
HTML Question

Load error using PHP variable in JavaScript

I am trying to execute a JavaScript command when the page loads, using PHP variable.

I am getting the following error:

Uncaught TypeError:

Cannot read property 'style' of null(…)


<head>
//cut out some stuff here
<script>
function openTab(tabName) {
var i, tabcontent, tablinks;
tabcontent = document.getElementsByClassName("panel_wrapper");
for (i = 0; i < tabcontent.length; i++) {
tabcontent[i].style.display = "none";
}
tablinks = document.getElementsByClassName("tablinks");
for (i = 0; i < tablinks.length; i++) {
tablinks[i].className = tablinks[i].className.replace(" active", "");
}
document.getElementById(tabName).style.display = "block";
console.log("fking debug "+tabName);
}
</script>
</head>
<body onload="openTab('<?php $_SESSION["loc"] ?>')">
//cut out some stuff here too
<body>


I've echoed
$_SESSION["loc"]
and it is "settings", a correct tab name that does work. Replacing the variable with "settings" didn't work either.

I know that something has not been set or something, hence it's null. Could it be something to do with PHP loading before the script?

NOTE: I'm still new to PHP, and the tab script code is by W3Schools.

Answer

The problem lies with this line:
<body onload="openTab('<?php $_SESSION["loc"] ?>')">
You are accessing $_SESSION["loc"], but you aren't echoing it. change that line to:

<body onload="openTab('<?php echo $_SESSION["loc"]; ?>')">