Getting javascript value into php variable

I want to get the value into php variable from javascript
if i do like this

<script>
var res = 50;
</script>

and php code
<?php echo "<script>document.write(res);</script>"; ?>

it works.
but,
i want to do like this

<script>
var res=0;
function add()
{
res =8;
}
</script>

<?php echo "<script>document.write(res);</script>"; ?>

it wont work. how can i do this?