I have a slider on my html page and I need to pass the input variable (I mean the percentage of slider, so the id) on a php variable in the same page. I've tried many methods, but no one has worked.
I attach my code below. I don't write here the style tag: ask me for it if you need.
<!DOCTYPE html>
<html>
<body>
<div >
<input type="range" id="my-slider" min="0" max="100" value="50" oninput="slider()">
<div id="slider-value">0</div>
</div>
<script type="text/javascript">
const mySlider = document.getElementById("my-slider");
const sliderValue = document.getElementById("slider-value");
function slider(){
valPercent = (mySlider.value / mySlider.max)*100;
mySlider.style.background = `linear-gradient(to right, #3264fe ${valPercent}%, #9c9c9c ${valPercent}%)`;
sliderValue.textContent = mySlider.value;
}
slider();
</script>
</body>
</html>
CodePudding user response:
One method of doing it is to set cookie and get it in PHP after changing the slide value reload it and you will see PHP echoing the result
<!DOCTYPE html>
<html>
<body>
<div >
<input type="range" id="my-slider" min="0" max="100" value="50" oninput="slider()">
<div id="slider-value">0</div>
</div>
<script type="text/javascript">
const mySlider = document.getElementById("my-slider");
const sliderValue = document.getElementById("slider-value");
function slider(){
valPercent = (mySlider.value / mySlider.max)*100;
mySlider.style.background = `linear-gradient(to right, #3264fe ${valPercent}%, #9c9c9c ${valPercent}%)`;
sliderValue.textContent = mySlider.value;
document.cookie=`sliderValue=${sliderValue.innerText}; expires=Never; path=\\`;
}
slider();
</script>
<?php
$svalue=$_COOKIE["sliderValue"];
echo $svalue;
?>
</body>
</html>
CodePudding user response:
Other way to do it is to use HTTP GET or POST requests
<!DOCTYPE html>
<html>
<body>
<form action="get.php" method="POST">
<div >
<input type="range" id="my-slider" name="svalue" min="0" max="100" value="50" oninput="slider()">
<div id="slider-value">0</div>
</div>
<input type="submit" value="Submit"></form>
<script type="text/javascript">
const mySlider = document.getElementById("my-slider");
const sliderValue = document.getElementById("slider-value");
function slider(){
valPercent = (mySlider.value / mySlider.max)*100;
mySlider.style.background = `linear-gradient(to right, #3264fe ${valPercent}%, #9c9c9c ${valPercent}%)`;
sliderValue.textContent = mySlider.value;
//document.cookie=`sliderValue=${sliderValue.innerText}; expires=Never; path=\\`;
}
slider();
</script>
</body>
</html>
get.php file
<?php
$myvar=$_POST["svalue"];
echo "Slide value is: " . $myvar;
?>