Tuesday 5 December 2017

Using PHP in javascript's IF Statement





I am trying to make a confirm box which will desire which php code
will be executed.
Heres my
code:



            type="text/javascript">
var answer = confirm('Are you
sure?');

if(answer==true)
{
$confirmation = 1; ?>

}
else
{


}

alert('')
alert(' defined("CONFIRMATION");
?>')




The
problem is , even if i click YES, $confirmation and boolean from defined() function
returns 1.
Whatever I click, (cancel or ok) one of them should be 0 (I've
already declared $confirmation before)
But both of codes at if and else blocks
are used!
Normally it works like this



Answer




You fundamentally misunderstand what PHP is
doing.



PHP is evaluated on the server before the
page is sent to your browser. By the time the browser sees it and executes the
javascript, all the PHP is gone.



Use your
browser's "view source" on the browser window with this code in it. You'll see it looks
like this:




            type="text/javascript">
var answer = confirm('Are you
sure?');

if(answer==true)
{
}
else

{
}

alert('1')

alert('1')



You
either need to implement what you want to do in javascript to run on the browser, or you
need to send a new request to the server and get a new page back (either directly or
indirectly) with your response.


No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...