really struggling to pass a JS variable to PHP variable. I understand that this cannot be done without passing from client to server and so I have tried to pass the variable via an AJAX call.
The code does not seem to be received by the PHP file as the passed variable does not echo after the AJAX call.
Here is my code although the most important element is right at the end. I am trying to pass JS variable 'chosenStudent' back to the PHP file.
$Content3 = <<<EOD
<form id="myGroupSelectForm" method="post">
<select id="selectGroup">
<option>Choose a Group</option>
</select>
<select id="selectStudent">
<option>Choose a Student</option>
</select>
</form>
<script type="text/javascript">
var select = document.getElementById("selectGroup");
var options = {$js_array_leadersGroupsName};
var i;
for(i = 0; i < options.length; i++) {
var opt = options[i];
var el = document.createElement("option");
el.textContent = opt;
el.value = opt;
select.appendChild(el);
}
</script>
<script>
var studentList = {$js_array_students_lists};
var select2 = document.getElementById("selectStudent");
var a = document.getElementById('selectGroup');
a.addEventListener('change', function() {
var i;
for(i = 0; i < options.length; i++) {
if ((this.value) == options[i]) {
var chosenStudentList = studentList[i];
}
}
var select = document.getElementById("selectStudent");
var length = select.options.length;
for (i = length-1; i >= 0; i--) {
select.options[i] = null;
}
var i;
for(i = 0; i < chosenStudentList.length; i++) {
var opt = chosenStudentList[i][0];
var el = document.createElement("option");
el.textContent = opt;
el.value = opt;
select2.appendChild(el);
}
}, false);
var b = document.getElementById('selectStudent');
b.addEventListener('change', function() {
var chosenSudent = this.value;
$.post('WickCustomLD.php', {variable: chosenSudent});
}, false);
</script>
EOD;
$Content3 .="\n";
if(!empty($_POST['variable'])) {
$chosenStudent = $_POST['variable'];
echo "<br>";
echo "<br>";
echo "<br>";
echo "<br>";
echo $chosenStudent;
}
return $Content3;
If anyone can help I would be very grateful.
$Content3before you access thevariable. Move the fragment at the end to the top of your file, or try to perform the AJAX request to a different PHP file altogether where you access the variable.