You cannot store a PHP value from javascript/jQuery without using AJAX.
After the DOM has been rendered, no additional PHP will run. That's it, all done. In order to send additional data to the server, you have two choices: (1) post a form to another PHP file, which will send the data typed into the form elements and will change/refresh the current page. or (2) use AJAX.
AJAX is a way to communicate with a separate PHP page, sending data back/forth, without refreshing/changing the page the user is on. An AJAX code block looks something like this:
$.ajax({
type: 'post',
url: 'ajax.php',
data: 'varName=' +varSomething,
success: function(d){
if (d.length) alert(d);
}
});
or
$.ajax({
type: 'post',
url: 'ajax.php',
data: 'varSomename=' +varValue
}).done(function(){
//success function
});
Data sent back from PHP is received in the AJAX code block's success
function (and ONLY there), where it can be manipulated and/or injected back into the DOM, like this:
$.ajax({
type: 'post',
url: 'ajax.php',
data: 'thevar=' +theval,
success: function(d){
$('#someDIV').html(d);
}
});
Here are some additional links re AJAX:
dynamic drop down box?
Prevent Page Load on Jquery Form Submit with None Display Button
When the data arrives at the specified PHP file (ajax.php in above examples), you can get that data via the $_POST[]
variable:
<?php
$summat = $_POST['someVarname'];
//To send data back to the AJAX success function, you just echo it:
$out = '<div style="font-size:3rem;color:blue;">';
$out .= $summat;
$out .= '</div>';
echo $out
Now you have the data in a local PHP variable. This variable will cease to exist when the PHP file execution is completed.
To retain the PHP variable, use a $_SESSION super-variable. In order to use the $_SESSION variable, you must add session_start()
to the top of the PHP page:
<?php
session_start();
$_SESSION['summat'] = $_POST['someVarname'];
//Now you have a permanent variable on the server, associated with this user's PHP session