Last active
December 11, 2018 09:32
-
-
Save danielemarino/c0a80908b7341639dfdd3f647853cd22 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php // Load items into a HTML select box via PHP & Ajax | |
$firstbox = $_POST['firstbox']; | |
$query = "SELECT * FROM mytable WHERE id_firstbox = '$firstbox';"; | |
$result = pg_query($query) or die('Query failed: ' . pg_last_error()); | |
$secondbox_arr = array(); | |
if (pg_num_rows($result) > 0) { | |
while ($row = pg_fetch_array($result, NULL, PGSQL_ASSOC)) { | |
$secondbox_arr[] = array("id" => $row['id_secondbox'], "name" => $row['testo_secondbox']); | |
} | |
} | |
echo json_encode($secondbox_arr); | |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<form> | |
<label>First Box: | |
<select id="firstbox" name="firstbox_name"> | |
<option value=" "></option> | |
<option value="1">Option 1</option> | |
<option value="2">Option 2</option> | |
<option value="3">Option 3</option> | |
</select> | |
</label> | |
<label>Second Box: | |
<select id="secondbox" name="secondbox_name"> | |
<option value=" "></option> | |
</select> | |
</label> | |
</form> | |
<script> | |
$().ready(function() { | |
var $secondbox = $("#secondbox"); | |
$("#firstbox").change(function() { | |
var firstbox_id = $(this).val(); | |
$secondbox.empty(); | |
if (this.value.trim() !== '') { | |
$.ajax({ | |
url: 'ajax.php', | |
type: 'post', | |
data: {firstbox: firstbox_id}, | |
dataType: 'json', | |
success: function (response) { | |
var len = response.length; | |
for (var i = 0; i < len; i++) { | |
var id = response[i]['id']; | |
var name = response[i]['name']; | |
$name.append("<option value='" + id + "'>" + name + "</option>"); | |
} | |
}, | |
error: function (exception) { | |
alert('Exception: ' + exception); | |
} | |
}); | |
} | |
}); | |
}); | |
</script> | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment