0

[SOLVED] Can I put JavaScript code inside a php block?

I'm doing a test project here as a beginner. The project consists only of entering name and age and then printing something on the screen. I already finished it in php but i have a progress bar working with Javascript. I would like that as soon as I press the button send it load the entire progress bar and then display the result but I don't know how to do it. I thought I could put the javascript code inside the php block to load progress first, but I believe it doesn't work. Help me! Follow my codes below (Some parts of the code are in Portuguese because I'm from Brazil and I don't speak English yet)  https://code.sololearn.com/W2b1gBdvqL6X/?ref=app

14th Dec 2020, 1:09 AM
Sorrayla Araujo
Sorrayla Araujo - avatar
1 Answer
+ 3
Yes, you can have JavaScript in a .php file. That's not your problem. You have PHP in your HTML-only file. That's your main problem. That's why PHP shows in the browser and can't be executed. You could get what you want by removing all of the PHP and using JavaScript to process your form instead. Sololearn won't let you submit a form to a PHP script you write there so converting to JavaScript is probably what you want. After removing your ?php section, you could replace your script content with this. The following also fixes the problem you mentioned where you want the progress bar changing only after clicking Submit:     var i = 0;     var progressBar = document.getElementById("bar");     function countNumbers(event){         if (i < 100){             i = i + 10;             progressBar.value = i;             // For browsers that don't support progress tag             progressBar.getElementsByTagName("span")[0].textContent = i;         // Wait for sometime before running this script again         setTimeout(countNumbers, 500);         } else { processForm(); } if (event) { event.preventDefault(); return false; }     } function processForm() { var nome = document.querySelector('input[name="nome"]').value; var idade = document.querySelector('input[name="idade"]').value; var message = '';         if (idade <= 12) {             message = "Olá " + nome + " você tem  " + idade + " anos e corresponde a categoria criança" ;         } else if (idade >= 13 && idade <= 30){             message = "Olá " + nome + " você tem  " + idade + " anos e corresponde a categoria Adolescente / Adulto";         }else{             message = "Olá " + nome + " você tem  " + idade + " anos e corresponde a categoria Terceira Idade";         } document.body.innerHTML = '<h2>' + message + '</h2>'; } var form = document.querySelector('form'); form.addEventListener('submit', countNumbers, true);
14th Dec 2020, 10:58 AM
Josh Greig
Josh Greig - avatar