PHP with Javascript Question

I know most posts are to solve problems, but I’m looking for advice about using PHP with Javascript. Also, I’m not sure if this is a PHP question or a Javascript question.

I have a webpage that are a combination of HTML, Javascript and PHP. The code is proprietary, so please don’t ask. The situation is this:

The PHP code gets information from a database and assigns it to various PHP variables. The Javascript is a function that get executed when the user selects from a set of radio buttons using an onclick event.

The function contains a set of conditionals of the form:

if(radio1 = *value*){
var x = y + <?php echo $*z*;?>;
.
.
}

The dilemma is that if the Javascript function is located below the PHP code, it works fine, but if it’s above the code, it doesn’t.

I know that PHP executes on the server and Javascript on the user’s device. I’ve always assumed that they execute asynchronously, so I don’t understand why they’re position sensitive.

I’d appreciate any insight someone on the forum could provide.

Thanks.

PHP is always executed first, on the server. The JavaScript runs later, on the user’s device.

I’d guess that your code generated invalid JavaScript due to undefined PHP variables when you position it above. The <?php echo $z; ?> is not delayed until the JavaScript runs, it is executed along with all the other PHP code when the page is requested so if the PHP code that defines $z is later on in the script, the PHP code will output nothing there as the variable is undefined. The result is JavaScript code that looks like:

if (radio1=value){
   var x = y + ;
}

Which of course is invalid and gives a syntax error.

Echoing variables directly into your JavaScript is not ideal in the first place. This is what things like data attributes are for. Echo your values into a data attribute on the relevant HTML elements, then use JavaScript to read that attribute value.

<input type="radio" id="radio1" data-z="<?=$z?>">

then

if (radio1 == 'whatever'){
   var x = y + radio1.dataset.z;
}

They wouldnt be. As kicken points out, make sure you’re not screwing up your PHP by rearranging the blocks such that you’re using a PHP variable before it’s defined.

Thanks Kicken. What you said makes sense, I just didn’t think of it that way. I wasn’t aware that I could do what you recommended, but will change the code accordingly. It’s a much cleaner approach. Again, many thanks.