The basic question: When specifically are the $_POST and $_GET variables set? The reason I ask is explained below.
Advance disclosure: The file I am sharing here is for testing/learning purposes, and doesn't aim to achieve anything useful. I wrote it in order to isolate this one question from the other details of the project I am working on.
Here's a summary of what I'm trying to do: I call a javascript function from a form
<form action="javascript:jsTest()" ... />
and then from within jsTest() I assign a javascript variable based on the return of a php function, phpTest():
var jsVar = <?php echo json_encode(phpTest()); ?>;
The function phpTest() simply returns a $_POST variable:
return $_POST['testName'];
Here's the full code:
<?php
session_start();
function phpTest() {
return $_POST['testName'];
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>javascript/php test</title>
<script type="text/javascript">
function jsTest() {
var jsVar = <?php echo json_encode(phpTest()); ?>;
alert(jsVar);
}
</script>
</head>
<body>
<form method="POST" name="testForm" action="javascript:jsTest()">
<input type="text" name="testName" value="username" />
<input type="submit" value="submit" />
</form>
</body>
</html>
The problem: alert always displays null.
I tested this in two ways. 1) If instead I set the form action to a separate .php file, the $_POST variables associated with the form input fields are set, and an echo in that file, of those $_POST values, is shown in the browser. And alternatively, 2) if instead I return from phpTest() a simple string,
return 'hello kitty';
then the javascript alert() shows exactly that returned string. Therefore I believe it is safe to assume that the $_POST variable has not yet been set. Which brings me to the question I have not been able to find an answer to:
When exactly are $_POST variables set? I assumed it was before page reload (which my approach requires), and I assumed this because if I alternatively use method="GET" in my code, I see the GET variables tacked onto the URL without any prior page reload.
Thanks in advance.
Chris