1

In the code below , a user selects a subject and the script below checks the subject selected and displays a list of topics options based on the subject the user selected.So my question is , is there a way to make the form in the script functional .in that is there a way to get the specific value of a topic the user selects.

<script>
function showUser() {
var subject=document.getElementById('subject').value;

if (subject == "maths") {
document.getElementById("form").innerHTML = "<?php echo"<form>
<select  id='topic'onchange='showuser()'>
<option value='algebra'>algebra</option>
<option value='calculus'>calculus</option>
</select></form>";?>";

var school=  document.getElementById("topic").value;

var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
  if (this.readyState == 4 && this.status == 200) {
    document.getElementById("txtHint").innerHTML = this.responseText;
  }
};
xmlhttp.open("GET","get.php?subject="+subject+"& topic="+topic,true);
xmlhttp.send();
return;
}
else if (subject =="English"){

document.getElementById("form").innerHTML = "<?php echo"<form>
<select  id='topic'onchange='showUser()'>
<option value='verbs'>verbs</option>
<option value='nouns'>nouns</option>
</select></form>";?>";

var topic=  document.getElementById("topic").value;
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
  if (this.readyState == 4 && this.status == 200) {
    document.getElementById("txtHint").innerHTML = this.responseText;
  }
};
xmlhttp.open("GET","get.php?subject="+subject+"& topic="+topic,true);
xmlhttp.send();
return;
}
else {
document.getElementById("form").innerHTML ="Invalid choice";
}
}
</script>
Luis
  • 43
  • 7
  • I think I see your problem and a few other things. First, Javascript renders in the front end, right? PHP renders server side. You can't get php code to execute if written to a page via javascript. Does that make sense? So your code `if (subject == "maths") { document.getElementById("form").innerHTML = "`, that php echo wouldn't actually run php code. The second issue, is that your
    tag, in order to submit a form, needs to have an action and a method. ie `
    `
    – John May 28 '20 at 18:02
  • Then when you submit the form, the data would be posted to `/some-php-file-to-grab-the-data.php`. You access these var via the `$POST` variable in PHP. You could also use `get` instead of `post`, accessing those vars via `$GET` in PHP. – John May 28 '20 at 18:05
  • If I understand correctly, chances are you don't need any php code to get this working. You probably want to use JS to grab the value of the selected option tag within a given select tag. See here: https://stackoverflow.com/questions/1085801/get-selected-value-in-dropdown-list-using-javascript – John May 28 '20 at 18:09

0 Answers0