Edit as per this comment:
You don't need any JavaScript to accomplish "post and redirect in one go".
Simply use your <input type="submit" id="gen" value="Generate" />
as it is and it should POST all data in the form to your PHP file. If you need other variables to be passed to your server, make a few <input type="hidden">
fields on your page and make their value
s your JS variables (using $("#input-id").val(yourVariable);
)
This Code answers the initial question
The Error in your Client-Side Code:
You specifically used the type
submit
in this button <input type="submit" id="gen" value="Generate" />
. What that does is tell the browser to stop everything and submit the nearest form. If you instead want to do something else with a button you have to use
$("#gen").on("click", function (e) {
e.preventDefault();
request = new XMLHttpRequest();
var url = "file.php";
var test = "data="+document.getElementById("test").value;
request.open("POST",url,true);
request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
request.setRequestHeader("Content-length", test.length);
request.onreadystatechange=checkResult;
request.send(test);
request.setRequestHeader("Connection", "close");
});
e.preventDefault();
tells your browser not to do what it was instructed to do by the type="submit
but rather run your js code.
The others are right you can get your data using $test = $_POST["data"];
. Here's why:
When sending your Data you build a x-www-form-urlencoded
string (this one: "data="+document.getElementById("test").value;
).
To you and to your connection, this is simply a String that gets appended to your request, but your Server (your file.php
) interprets this as an associative array, meaning a Data Structure with a key
(data) and a value
(document.getElementById("test").value
). When you submit a form your browser does this automatically, it appends all data in the form to your request and sends it to the server that way.
Every request with added data follows this pattern. When you take a look at YouTube for Example, their video-urls all contian ?v=...
. If you wanted to built YouTube in PHP you would get the variable using $video = $_GET["v"]
.