[Solved] Pass variables from Javascript to PHP – Popup/Modal Window


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.

solved Pass variables from Javascript to PHP – Popup/Modal Window