0

I'm making a school project, and I need to transfer a javascript variable to php, like, I have a javascript function called "acertou" the translation doesn't matter, but it is this:

function acertou() {
        acertos++;
        <?php $batata++; ?>
        alert(acertos + "\n" + <?php echo $batata ?>);
    }

This is a quiz, and "acertou()" is called when the person awnswers the correct option, the function increases "acertos" that is the number of correct hits and "batata" (that actually is translated as "potato" -- I don't know why) is the PHP version of the variable, but $batata doesn't increases, the alert result is:

1
1

2
1

3
1

[and keeps going]
this function is the only place when $batata is called or modifyed

tlckpl
  • 59
  • 1
  • 8
  • 1
    PHP runs before the page is rendered, javascript after. If you want to update it on the PHP side, use ajax to pass it back and forth. – aynber Apr 10 '17 at 16:25
  • 1
    PHP is a language that runs on the server and *generates* a webpage, consisting of HTML, Javascript and CSS. Once it does this, it's no longer running. When your browser is showing/running the page, the PHP is long since done executing. – gen_Eric Apr 10 '17 at 16:25

1 Answers1

1

This is very confusing for beginners, I recall asking to same question as you years ago.

PHP is server side, JavaScript is client side.

Allow me explain how it goes: When you request a web page the server will preprocess all your PHP files and transform them into HTML, so all dynamic aspects (variables, functions) will be rendered into static HTML page, thus it will first execute your code, with $batata++ executed, it will be equal to 1. Then it will transform your code into HTML file, generating:

function acertou() {
     acertos++;
     alert(acertos + "\n" + 1);
}

Just look at the source code of your page :)

So what you need to understand is that PHP is executed on the server, say read some data from a database and render it into HTML, which is then seen by the user. The user can never see the server code. Just think about it :)

Enjoy programming!