I want to create a quiz with some questions($_SESSION['allquestions']). Now I want to add a progress bar for some nice visuals why I used this code:
<?php if($_SESSION['answeredquestions']>0){
$goal=$_SESSION['allquestions'];
$done=$_SESSION['answeredquestions'];
echo $done/$goal;}
?>
<body class="small-container text-center " style="font-family: 'Times New Roman', Times, serif;
font-size: 40px;
color:#45A29E;">
<div class="progress">
<div class="progress-bar" role="progressbar" style="width: 10%;" aria-valuenow="25" aria-valuemin="0" aria-valuemax="100">25%</div>
</div>
<script type="text/javascript">
var bar = document.querySelector(".progress-bar");
function makeProgress(){
bar.style.width = (<?php $_SESSION['anweredquestions']/$_SESSION['allquestions']?>*100) "%";
bar.innerText = (<?php $_SESSION['answeredquestions']/$_SESSION['allquestions']?>*100) "%";
}
makeProgress();
</script>
My calculation is working which proofs something in those variables and if I put a number instead of those two variables, it works! But as soon i put both together the bar says Nan. How can I convert it to an int? If anyone knows what I could try, I'd be very glad! Thank you in advance.
CodePudding user response:
please check for things below:
make sure you initialize your session data by calling session_start() in your script.
fix your typo in the first line of makeProgress() function where you wrote $_SESSION['anweredquestions'].
result of php calculation should be printed in the page if you want to use it as a css property value. so change lines of makeProgress() function like so:
bar.style.width = "<?php echo $_SESSION['answeredquestions'] / $_SESSION['allquestions'] * 100 . "%" ?>" bar.innerText = "<?php echo $_SESSION['answeredquestions'] / $_SESSION['allquestions'] * 100 . "%" ?>"
thanks for your attention, best regards ;)
CodePudding user response:
The error is saying that it required number and what's it receive isn't number. So there's a small glitch I can see from you code. First you have to add quotes around the php code to inject as a CSS or value from JS code.
Here I'm assuming that you've valid value in your session variables. If not check it first.
Also check I have changed code bit based on assumption that you want to get percentages and want to perform division operation first and then multiply it by 100
function makeProgress(){
bar.style.width = "<?php ( $_SESSION['answeredquestions'] / $_SESSION['allquestions'] ) * 100; ?>" "%";
bar.innerText = "<?php ( $_SESSION['answeredquestions'] / $_SESSION['allquestions'] ) * 100; ?>" "%";
}
This should work for you.