I am developing a web app using Laravel 5 and trying to integrate some JS to help out a form. I want users to be able to select a category in one select field, at which point a second select field should populate with options within that category. (E.g., Select a profession: programmer, artist. If 'programmer' is selected, second select field populates with: C++, Java, Python. If 'artist' is selected, second select populates with: Photoshop, Illustrator, MS Paint.)
Note that I need to populate these fields from my database. I've found examples of what I am trying to do on the web that I have tried to adapt to my case. The one I'm using is here: http://ift.tt/1l1OL4i but I can't get it to work (it's fairly old--from 2010).
Here's my HTML and JS:
<!-- JS Code -->
<script type="text/javascript">
$(document).ready(function()
{
$(".profession").change(function()
{
var id=$(this).val();
var dataString = 'id='+ id;
$.ajax
({
type: "POST",
url: "ajax_skill.php",
data: dataString,
cache: false,
success: function(html)
{
$(".skill").html(html);
}
});
});
});
</script>
<!-- HTML Code -->
<label>Profession: </label>
<select name="profession" class="profession">
<option selected="selected">--Select Profession--</option>
<?php
$professions = App\Profession::all();
foreach($professions as $profession){
echo "<option value=\"" . $profession->id . "\">" . $profession->name . "</option>";
}
?>
</select>
<label>Field :</label>
<select name="skill" class="skill">
<option selected="selected">--Select Skill--</option>
</select>
Here's what ajax_skill.php looks like:
<?php
use DB;
if($_POST['profession'])
{
$id = $_POST['profession'];
$skills = DB::table('skills')->where('profession_id', '==', $id)->get();
foreach($skills as $skill)
{
echo "<option value=\"" . $skill->id . "\">" . $skill->name . "</option>";
}
}
?>
As far as I can tell, nothing runs from ajax_skill.php. I tried echoing something out in that function, it didn't appear on my page, and the skills field never populates. The profession select field, however, populates fine.
Any thoughts on where this code is going wrong?
via Chebli Mohamed
Aucun commentaire:
Enregistrer un commentaire