0

I want to use javascript variable as php variable. I am echo php variable then its print. but when i am use for fetching data from database its show an error Notice: Undefined index: document.write(i)

here my code

javascript

var i=0;
function inc()
{
    i+=1;
}
<?php $foo="<script>document.write(i)</script>"; ?>

php

code work for

echo $foo

code not work for

$i=$foo;
$query="select * from TABLE where id = $i";
$result=mysqli_query($conn,$query);
while($row=mysqli_fetch_row($result))
    {
        echo $row[0];
    }

Then It show This Error Notice: Undefined index: document.write(i)

prashant kushwah
  • 121
  • 1
  • 3
  • 15
  • php code is executed in the server side before javascript code (in the browser) in your case, if you want to pass variables to php you can use GET variables, POST variables etc ... – smarber May 30 '17 at 10:23
  • Ref this- https://stackoverflow.com/questions/21721461/use-javascript-variable-in-php-code – Suresh May 30 '17 at 10:25
  • Possible duplicate of [Use javascript variable in php code](https://stackoverflow.com/questions/21721461/use-javascript-variable-in-php-code) – Red Bottle May 30 '17 at 10:30

2 Answers2

0

PHP is server-side code that is run to generate a page. Javascript is client-side code that is run after the page is sent to the visitor's browser. Javascript can't affect the server-side code because the server code is done running by the time the Javascript runs. If you want to have a user's selection change the behavior of the PHP code the next time the form is loaded, pass a variable through a $_POST variable when the form is submitted.

If you want your PHP and Javascript code to be using the same value, have the PHP code write a Javascript variable initialization into the page's <head> section before any Javascript would run that would need to use it.

FKEinternet
  • 1,050
  • 1
  • 11
  • 20
-2
<script>
var i=0;
function inc()
{
    i+=1;
    return i;
}

</script>
<?php
$foo = '<script type="text/javascript">document.write(inc());</script>'; //Script function call which return the var i value to php variable

echo $foo;
?>
Ashu
  • 1,320
  • 2
  • 10
  • 24
  • 1
    this isn't going to work as expected - `$foo` is going to contain the literal string `''` not the result of the Javascript running. – FKEinternet May 30 '17 at 10:31
  • 3
    While this code may answer the question, providing additional context regarding how and/or why it solves the problem would improve the answer's long-term value. – Badacadabra May 30 '17 at 13:10