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.

3
  • 2
    you have to either submit a form, or make an ajax request (ie XMLHttpRequest) Commented Apr 24, 2015 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 Commented Apr 24, 2015 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. Commented Apr 24, 2015 at 20:24

2 Answers 2

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
?>
Sign up to request clarification or add additional context in comments.

Comments

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

3 Comments

Always a pleasure man :) - I'll test next time before I post, wasn't 100% sure
This only appears to work, you are not actually typecasting int_val, you are trying to typecast the string <script>document.write(int_val);</script>. $toInt will actually equal 0. Try doing a var_dump($toInt) to see.
patrick, you are right, its giving me type as integer but value is zero. same problem as Torean's link

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.