0

I want to pass the answer of a JavaScript function call to a PHP variable so that I can use else where in the PHP script.

I have the JavaScript code below

<script type="text/javascript">
    function showSelected(val)
    {
        document.getElementById('selectedResult').innerHTML =  val;
    }
</script>

I would want to save the answer of the method call in a PHP variable to be used elsewhere in the PHP script.

I tried this but it's not working

<?php
    $val = "<script type='text/javascript'>showSelected();</script>";
 ?>

Someone kindly assist.

  • By answer of the call do you mean the value of `val` ? – kiranvj Jan 24 '19 at 05:43
  • @kiranvj I would want to save the result of the JS function showSelected() to the PHP variable $val. –  Jan 24 '19 at 05:45
  • I didnt get what the result is. That function is not returning anything. – kiranvj Jan 24 '19 at 05:46
  • @kiranvj assuming the result of the function call is "Variable Two". That is the variable I would want to pass to the PHP variable $val. –  Jan 24 '19 at 05:48
  • 2
    Possible duplicate of [How to pass JavaScript variables to PHP?](https://stackoverflow.com/questions/1917576/how-to-pass-javascript-variables-to-php) – l'L'l Jan 24 '19 at 05:50
  • @kiranvj when I print out on the screen as
    , it outputs the desired result.
    –  Jan 24 '19 at 05:51
  • Okay, so you need to send the value of val to your PHP scripts, You can do it via Ajax without refreshing the page. Please check the link posted above by I'L'I – kiranvj Jan 24 '19 at 05:54
  • Php is server side and js is client side. You can send the data via 1. a form post/get OR 2. by ajax – varun sharma Jan 24 '19 at 07:04

2 Answers2

0

You need to return something from the javascript function. If you don't need to return anything at least return true. It is a good practice.

<script type="text/javascript">
function showSelected(val)
{
    document.getElementById('selectedResult').innerHTML =  val;
    return val;
}

You also need to pass a variable when the function is called in the php script.

<?php
$val = "<script type='text/javascript'>showSelected('something');</script>";
?>

Although according to your requirement, you should return the value you need.

0

You have to pass an argumentValue since your javascript function definition accepts one parameter. Also your javascript function need to return the value in order to use it outside the function or to assign it to a php variable.

   <script type="text/javascript">
    function showSelected(val)
    {
        document.getElementById('selectedResult').innerHTML =  val;
        return val;
    }
    </script>

    <?php 
     $val = "<script type='text/javascript'>showSelected('argumentValue');</script>";
    ?>