I have a single form input on my homepage userinput
. The homepage also contains a JavaScript function that uses that userinput
value to calculate a result.
<form action="/run.php" method="POST" target="_blank">
<input type="hidden" id="idg" value="<?php echo $rand ?>"> // gets random url, can be ignored
<input type="text" name="userinput" id="userinput">
<button type="submit" onclick="calcResult();">Go!</button>
</form>
<script>
function calcResult() {
var userinput = document.getElementById('userinput').value;
var result = userinput + 10; // want to POST result in a hidden input field w/ form
</script>
I'm trying to find a way in which a user can enter their input, submit the form, the JavaScript takes that userinput
and calculates a result, then that result is POST'ed along with the userinput
in the form.
The problem I can forsee with this method is that:
- The JavaScript function needs the
userinput
before it can calculate the result. However, the only way to get theuserinput
is to submit the form, which means the form data will be POSTed before the JavaScript result is returned.
My attempted solution(s):
- I've been attempting to use AJAX (Unable to access AJAX data [PHP]) and have been consistently running into issues with that.
I was wondering whether it's possible to use a button (type="button"
), instead of a submit (type="submit"
) for the form. Then just use that button to call the JS function, then (somehow) submit the form (with the JS function result) after the JS function has completed? (either with plain JS or jQuery).