0

I want to assign javascript variable value to php variable. I am new to this and not able to achieve the same. Below is my code:

<script type="text/javascript">
    function foo(sampleValue) 
    {
        var table = document.getElementById('mytable');
        var answer = table.rows[sampleValue].cells[1].innerText;
        alert (answer);
        window.location.href = "show.php?w1=" + answer;
    }
</script>

<?php
    if(isset($_POST['shwData']))
    {
        if(isset($_GET['w1']))
        {
            echo "this is it";
        }
    }
?>
sazzy4o
  • 3,073
  • 6
  • 34
  • 62
Coder157
  • 73
  • 3
  • 15
  • 4
    you can't. javascript runs on the client, php runs on the server. if you want JS to "set" something in php, you'll have to send it back to the server, usually by ajax. – Marc B Aug 24 '15 at 21:10
  • Can you provide code snippet for the same ? – Coder157 Aug 24 '15 at 21:12
  • @MarcB He's sending the variable using a redirection with a GET parameter in the URL ;) `"show.php?w1=" + answer` – blex Aug 24 '15 at 21:12
  • This answer has some nice examples on how to do an AJAX call. http://stackoverflow.com/questions/5004233/jquery-ajax-post-example-with-php – Nelson Teixeira Aug 24 '15 at 21:18

2 Answers2

2

Have you tried omitting the first if condition?

if(isset($_GET['w1'])) {
  echo "this is it";
}

BTW: Of course you can "pass a variable from a javascript to a php script". This has to be done via an additional request. Just like you have explained it with window.location.href = "show.php?w1=" + answer;. This is definetely an option.

Depending on what you want to achive with this value, and why in that moment, you could think about using AJAX. Just send a request to the server, if it has to do some action with a given array of (post-) data.

ILCAI
  • 1,164
  • 2
  • 15
  • 35
  • I tried without first condition but it did not work. – Coder157 Aug 24 '15 at 21:20
  • 1
    What are you checking for with the first condition? If you're relocating with javascript then you're not "posting" so no ``POST`` values will be set. Only your ``GET`` values will be received this way. To send values via ``POST`` you'll have to submit a form or use AJAX. Removing the first condition _should_ fix the problem. – Vic Aug 24 '15 at 21:32
0
You can do something like this:

<script type="text/javascript">
    function foo(sampleValue) 
    {
        var table = document.getElementById('mytable');
        var answer = table.rows[sampleValue].cells[0].innerHTML;

        alert (answer);
        window.location.href = "show.php?w1=" + answer;
    }


</script>
<table id="mytable">
    <tr>
        <td>my cell</td>
    </tr>
</table>

 <button onclick="foo(0)">Click me</button> 

<?php
        if(isset($_GET['w1']))
        {
            echo "this is it";
        }

?>