How to get the html Select value in php?
i have made this Select in html
<select id="year" onchange="filterYear();">
</select>
Function to fill in the Select:
var n = 22;
function selectOne() {
var select = document.getElementById('year');
for (var i=5; i<n; i ) {
select.options[select.options.length] = new Option(i 1, i);
}
}
but i need to read the current selected item from the select.
i tried this (javascript):
function filterYear() {
var e = document.getElementById('year');
var value = e.value;
var text = e.options[e.selectedIndex].text;
alert(text);
}
php:
$text = $_GET['text'];
echo $text;
but this did not work any ideas on how to fix this
i hope someone can push me in the right direction
CodePudding user response:
Without submitting a form and thus reloading the page you can easily send an ajax request that can be processed by the PHP server script. The response from the server is then used in the callback to, usually, perform further DOM manipulation or whatever.
var n = 22;
function selectOne() {
var select = document.getElementById('year');
for( var i = 5; i < n; i ) {
select.appendChild( new Option( i 1, i ) );
}
}
// build the menu
selectOne();
// bind event listener externally
document.getElementById('year').addEventListener('change',e=>{
// a callback to process response from PHP script
let callback=(r)=>{
alert(r)
};
// send a GET ajax request and process response
fetch( 'path/to/php/script.php?text=' e.target.value )
.then(r=>r.text())
.then(callback)
.catch(alert)
})
<select id="year" name='year'>
</select>