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)

3
  • 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 ... Commented May 30, 2017 at 10:23
  • Ref this- stackoverflow.com/questions/21721461/… Commented May 30, 2017 at 10:25
  • Possible duplicate of Use javascript variable in php code Commented May 30, 2017 at 10:30

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

-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;
?>

2 Comments

this isn't going to work as expected - $foo is going to contain the literal string '<script type="text/javascript">document.write(inc());</script>' not the result of the Javascript running.
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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.