1
<script type="text/javascript">
    var int_val = 111;
</script>

<?php
    $js_int_val_in_php ='<script>document.write(int_val);</script>';
    echo $js_int_val_in_php; // 111
    echo '<br>';
    echo gettype($js_int_val_in_php); // string  
    // but I want it as an integer
    // even settype(); does not help!!
?>

Anyone has any good idea how do I pass js integer value as integer in PHP?? I love jQuery but in this situation, please no jQuery suggestion.

  • 2
    you have to either submit a form, or make an ajax request (ie [XMLHttpRequest](https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest)) – Patrick Evans Apr 24 '15 at 20:23
  • you can not assign java script variable value to php variable. This is because PHP is a server side scripting language and javascrpt is client side. If you need JavaScript value in php for server side execution then you can use ajax – Manish Shukla Apr 24 '15 at 20:23
  • 1
    Welcome to SO. You can cast the value. But I think you have the wrong idea about how this should work, JavaScript executes in the browser and not within PHP. – Twisty Apr 24 '15 at 20:24

2 Answers2

0

You are confusing server-side variables with client-side variables,

You need to the data to the server, otherwise the server only knows the variable name, which is a string

<script>
var int_val=111;
function doAjax()
{
var xmlhttp;
xmlhttp=new XMLHttpRequest();
xmlhttp.open("GET","index.php?v="+int_val,true);
xmlhttp.send();
}
</script>
<a href="javascript:doAjax();">click here to send data to server</a>
<?php
$int_val=''
if (isset($_GET['v']))
{$int_val=intval($_GET['v']);}
//now you can access the `int_val` after the JS function ran
?>
Uri Goren
  • 13,386
  • 6
  • 58
  • 110
0

I think that the question was already asked here: Unable to convert string to integer in PHP

If you want, you can also look at PHP typecasting here: http://php.net/manual/en/language.types.type-juggling.php#language.types.typecasting

and maybe have something like this?

<script type="text/javascript"> var int_val = 111</script>
<?php
    $js_int_val_in_php = '<script>document.write(int_val);</script>';
    echo $js_int_val_in_php; // 111
    echo '<br>';
    $toInt = (int) $js_int_val_in_php;
    echo '<br>';
    echo gettype($toInt); // string  
?>

I haven't tested but I'm sure the typecasting should do the trick, don't forget to have a look at the URL I sent first

Community
  • 1
  • 1
TrojanMorse
  • 642
  • 1
  • 8
  • 16
  • Always a pleasure man :) - I'll test next time before I post, wasn't 100% sure – TrojanMorse Apr 24 '15 at 20:47
  • This only appears to work, you are not actually typecasting `int_val`, you are trying to typecast the string ``. `$toInt` will actually equal 0. Try doing a `var_dump($toInt)` to see. – Patrick Evans Apr 24 '15 at 21:24
  • patrick, you are right, its giving me type as integer but value is zero. same problem as Torean's link – TheLittleHenry Apr 24 '15 at 21:32