-4
<html>
<head>
        <script type="text/javascript">
            function showdivv(el, idclicked) {
                var iddd = idclicked;
                var display = document.getElementById(el).style.display;
                if(display == "none")
                    document.getElementById(el).style.display = 'block';
                else
                    document.getElementById(el).style.display = 'none';
            }
        </script>
        <?php  $showw = "<script>document.write(iddd)</script>"; ?>
</head>
<body>
    <div id="myDiv" style="display: none;">ID Selected: <?php echo $showw; ?></div>
    <?php $variable = 4; ?>
    <button type="button" onclick="showdivv('myDiv', '<?php echo $variable; ?>')">Show / Hide</button>
</body>

I'm trying to make a way when a person presses the button pass the variable, in this case ID, to JavaScript and then show the hidden div in PHP. It does not work, can someone help me? THX

Daniel Garcia
  • 1
  • 1
  • 1
  • 3

1 Answers1

0

If you're okay with the page reloading, you can simply do

window.location.href('php_script_that_needs_your_input.php?id=input_id_from_js');

If not, I absolutely recommend using JQuery as it makes Ajax queries a breeze.

Inside the <head> tags:

<script src='http://code.jquery.com/jquery-2.2.0.min.js'></script>

Upload the script to your own server for production purposes, obviously.

in the <body>, where you want the results from the PHP script to appear (skip this if you don't want output from PHP):

<div id="phpResult"><!--content to be set by ajax--></div>

and put this JS directly below this <div>:

function ajax_on_button_press(resultDiv, id) {
   var phpUrl = "php_script.php?id="+id+"&other_variable=cheese&more_info=rats";
   $(resultDiv).load(phpUrl);
}

I have used example values here, but you can easily use variables from JavaScript like this:

var other_variable=$('#otherVariableInput').val(); //gets input from a textbox with the html id otherVariableInput
var phpUrl = "php_script.php?id="+id+"&other_variable="+other_variable+"&more_info=rats";

To start the process, you need a button that runs this script. Change your button markup to

<button type="button" onclick="ajax_on_button_press('#phpResult', '<?php echo $variable; ?>')">Show / Hide</button>

If I have understood you correctly, that should solve your problem.

Bjonnfesk
  • 298
  • 2
  • 13