I'm having troubles when making a linked list in HTML, let me explain:
In HTML I have this two selects:
<!-- This select WORKS and read the opened projects from de database -->
<select name="project" id="project">
<option value="0">Select a project</option>
<?php if (isset($result2)): ?>
<?php foreach ($result2 as $res): ?>
<option value=<?php echo $res['c_project_id'] ?>><?php echo $res['d_name'] ?></option>
<?php endforeach ?>
<?php endif ?>
</select>
<!-- This doesn't work, but I want: When I select a project, the project's categories go here -->
<select name="category" id="category">
</select>
The REAL DATA are the next: Table PROJECT
c_project_id | d_name | d_description | n_budget | d_state
1 | Test | Test Project | 100 | Open
2 | Web | Web APP | 3000 | Open
3 | C Test |Closed Project | 100 | Closed
4 | Certif.| Certificates | 2500 | Open
Table Categories (conected with table project)
c_category_id | d_name | d_description | c_project_id
1 | General| General cat | 1
2 | Test | Test cat | 1
3 | General| General cat | 2
4 | General| General cat | 3
5 | Nothing| Nothing cat | 3
6 |Program | Programming | 2
...
I have a SELECT in html that takes the project name and ID, this works in the select nº1
$statement2 = $conexion->prepare("SELECT c_project_id, d_name FROM project WHERE d_state= 'Open'");
$statement2->execute();
$resultado2 = $statement2->fetchAll();
Now I want: When I "click" in the first select, the second select make the statement and fulfill the second select. For testing, I just wrote a simple option. I tried with AJAX and PHP but the 2nd option is empty:
AJAX:
$( "#project" ).change(function() {
var select = $( "#project option:selected" ).val();
console.log(select); //just for testing that I took the value.
$.ajax({
type: "POST",
url: "phpPage.php",
data: { selectedProject : select }
}).done(function(data){
console.log("Done");
$("#category").html(data);
});
});
AND PHP:
if(isset($_POST["selectedProject"])){
$proy = $_POST["selectedProject"];
$output = "<option value='100'> Select your category </option>";
if($proy != 0){
$output.= "<option>" . $proy . "</option>";
}
echo $output;
}
But this return me nothing, all is empty.
FINALLY, when I tried to debug, I noticed that in one of the PHP responses, the HTML code () is been written at start of the page (in the response):
<option value='100'> Select your category </option><option>1</option>
<!DOCTYPE html>
<html lang="es">
<head>
<title>
...
Sorry for that huge question, but I'm wasting a lot of time with that and I don't know what could happen. Thanks you!