0

So right now I have this JS code:

function scoreCalculation(random, userPick) {
  if (userPick === random) {
    userScore++;
    winner.innerHTML = `<h3><font color="green">You won</font></h3>`;
  }
}

Which basically adds +1 to a score and shows in an html.

What I'm trying to achieve is to add that score into the database using update_user_meta PHP when userPick===random.

I'm trying to execute this PHP (tested and working) inside the javascript code:

<?php   $current_user = wp_get_current_user();
    $current_user_id =  $current_user->ID;
    $user_coins = get_user_meta( $current_user_id, 'usercoins' , true );
    $user_coins_sum_plus = $user_coins + 1;
                
update_user_meta( $current_user_id, 'usercoins', $user_coins_sum_plus);

?>

I have tried this mix, but it doesn't work. Basically JS code stops working at all:

function scoreCalculation(random, userPick) {
  if (userPick === random) {
    userScore++;
<?php   $current_user = wp_get_current_user();
    $current_user_id =  $current_user->ID;
    $user_coins = get_user_meta( $current_user_id, 'usercoins' , true );
    $user_coins_sum_plus = $user_coins + 1;
    $user_coins_sum_minus = $user_coins - 1;
                
update_user_meta( $current_user_id, 'usercoins', $user_coins_sum_plus);

?>;
winner.innerHTML = `<h3><font color="green">You won</font></h3>`;
  }

I guess I'm making a slight mistake adding the php inside the javascript?

Any help would be appreciated.

Dharmaraj
  • 47,845
  • 8
  • 52
  • 84
r0naldinio
  • 171
  • 6
  • PHP code runs on the server. The result is sent to the browser, where the HTML is parsed and JS scripts are executed. To run PHP code from inside JS (without leaving the page), you need AJAX/fetch. –  Aug 24 '21 at 11:19
  • 4
    Duplicate: [What is the difference between client-side and server-side programming?](https://stackoverflow.com/questions/13840429/what-is-the-difference-between-client-side-and-server-side-programming) –  Aug 24 '21 at 11:20

1 Answers1

4

You can't use PHP code inside the javascript file like this. For that, you have to use Ajax and Jquery and pass data in Ajax call to PHP file. You can refer Jquery and ajax documentation. Read https://jquery.com and https://api.jquery.com/jquery.ajax/

You have to pass those data to the javascript file by form or data attributes. After that, you can call PHP file using ajax and execute your code what you want.

    $current_user = wp_get_current_user();
    $current_user_id =  $current_user->ID;
    $user_coins = get_user_meta( $current_user_id, 'usercoins' , true );
    $user_coins_sum_plus = $user_coins + 1;
    $user_coins_sum_minus = $user_coins - 1;
    
    update_user_meta( $current_user_id, 'usercoins', $user_coins_sum_plus);

For example, This will works

alert( <?php echo "'Hello'"; ?> );

But you can't perform any operation like this:

function my_function()
{
<?php
$num1 = 2;
$num2 =3;
$sum = $num1 + $num2;
echo $sum;
?>
}