1

Okay, here are something I have now.

I'd like to use $_SESSION['pass'] in my other php files to make it as a condition to check whether an if condition is true. But it seems that the system only shows the alert part and never runs the code in the PHP tag. Thanks a lot!

document.getElementById('pass').onclick = function(){
    <?php $_SESSION['pass']=1; ?>
    alert('here!');
}
document.getElementById('fail').onclick = function(){
    <?php $_SESSION['pass']=0; ?>
    alert('there!');
}
Lykas
  • 117
  • 10
  • Please add your code to the question rather than an image of the code – Professor Abronsius Jul 22 '18 at 09:43
  • Sorry, since the system keeps on sending me an warning of the code, which prevent the post from being post. Now modified! – Lykas Jul 22 '18 at 09:51
  • 1
    JavaScript runs on the client. PHP runs on the server. Unless JavaScript is calling PHP on the server what you have there isn't going to work. Take a look at [this post](https://stackoverflow.com/questions/2034501/why-php-script-is-not-workig-in-a-web-browser) for a good explanation and further links. – Dave Jul 22 '18 at 09:52
  • 2
    PHP and js don't work together like that. When the resource containing that code is requested, first all PHP code runs. Which means `$_SESSION['pass']` is set to 0, given that that's the later statement. Then the result of the script is sent to the client, which is the JS minus the PHP parts. If you want to run PHP code based on a button click, you need to run an AJAX request. –  Jul 22 '18 at 09:53
  • Thanks, but how can I make javascript calling PHP or simply make it work. Still new to PHP and js. – Lykas Jul 22 '18 at 09:54
  • AJAX is the tool to call PHP on the server from JS. – Dave Jul 22 '18 at 09:54
  • @Dave Thanks, I will go check it out. – Lykas Jul 22 '18 at 09:57

1 Answers1

1

PHP is a server-side scripting language whereas JavaScript is a client-side scripting language. PHP runs in the back end on the server whereas JavaScript runs in the front end on the browser. PHP can be used to generate dynamic content for the browser. In your case, it seems like you want to set value of a session variable based on condition in the JavaScript code. PHP blocks in your code are executing in first place on the server which runs all PHP blocks by first setting $_SESSION['pass'] as 1 and then to 0 in the next PHP block. The resulting HTML is then sent to the browser for display. If you want to change the value of session variable based on the button user clicks, then you will need to do it using AJAX request.

Striezel
  • 3,693
  • 7
  • 23
  • 37
Ahmed Numaan
  • 1,034
  • 1
  • 10
  • 26