Hi I've successfully passed Javascript variable to PHP, but however the value I pass does not seem to be recognized as integer or string.

For e.g.

<script language="Javascript">
var x; 
x = 1;
</script>

<?
$y = "<script language=\"Javascript\">document.write(x)</script>";

$q="Select * from table where id = $y";
//id is an integer field in database

$r = mysql_query($q) or die ("Select query failed");

//The Query Fails every time. If I give id=1 or id=2, it works fine. 

?>

What can the problem be. If i give in PHP, the value of $y=1 directly it works fine.

If I convert the $y using intval($y), it returns me 0

It is not making me any sense, please help me.

Thanks

    Try:

    echo $q;
    

    ..after the query initialization and you'll know why it doesnt work 🙂

      Hi i did try echo it comes normal like
      Select * from table where id = 1

      but still the query fails, however, if i hard code the value 1 in the query, it works fine. little weird.

      though after getting the value from javascript, it try to convert it to integer using intval, but it converts it into 0

      Any Idea

        The PHP code is interpreted server side. The Javascript code is interpreted client side. Consequently, what you are doing is running the invalid query:

        $q="Select * from table where id = <script language=\"Javascript\">document.write(x)</script>";

          No, this cant be. If you do this:

          $y = "<script language=\"Javascript\">document.write(x)</script>";
          
          $q="Select * from table where id = $y";
          

          Your query will be:

          $q="Select * from table where id = <script language=\"Javascript\">document.write(x)</script>";
          

          ..or you have left off something that I dont know. Javascript is a clientside language so you cant mix it with php just like that. Either you'll have to use ajax or send the information somehow to the script so PHP knows about it.

            thanks for the information, i tried it, but it gives the same error, query failed, but if i hard code the same value, it works. anyways i think i need to look at AJAX for this sort of issues.

            thanks to both of you for help

              Write a Reply...