0

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 the userinput is to submit the form, which means the form data will be POSTed before the JavaScript result is returned.

My attempted solution(s):

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).

3
  • 2
    You seem to be missing a closing bracket for your calcResult() function. More importantly, you don't need to use AJAX for this... unless you are trying to submit the form without reloading the page... Why not just do the calculations on the server (PHP) side? Commented Mar 10, 2017 at 17:15
  • @Mikey That missing bracket isn't the case in the proper code, this is just the shortened, useful part of it. The page is reloading, so I would rather not use AJAX, I just don't know how I can run the JavaScript function (using the userinput before the form POST's) Commented Mar 10, 2017 at 17:19
  • @Mikey Because they are JavaScript algorithms, that I can't rewrite (yet). Plus the result of the JavaScript function needs to be inserted into my database, so has to be changed to PHP. Commented Mar 10, 2017 at 17:21

5 Answers 5

1

there are multiple approaches to do this,

i'm gonna use jquery here instead of pure javascript to simplify it

[without submission] you may check the event change

$('#userinput').change(function (e) {
    // make some calculation
    // then update the input value
});

[with form submission] you will disable the submission using the object preventDefault inside the submit event

$('#userinput').submit(function (e) {
    e.preventDefault();
    // make some calculation
    // then update the input value

    // your ajax goes here OR resubmission of your form
    // to resubmit the form
    $(this).submit();
});
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you for these suggestions. One question: How would I go about resubmitting the form after the calculation are completed (using the [with form submission] code you wrote)?
so ? do you still have the same issue ?
0

What you will find useful in this scenario is event.preventDefault();

function calcResult(e) {
    // Prevent the default action of the form
    e.preventDefault();

    var userinput = document.getElementById('userinput').value;
    var result    = userinput + 10;

    // Do whatever else you need to do

    // Submit the form with javascript
    document.getElementById("myForm").submit();
}

1 Comment

If I add onclick="calcResult(event)" to my button, then that submits without any console errors, however if I add the hidden field <input type="hidden" name="hiddeninput" id="hiddeninput"> and within the function write document.getElementById('hiddeninput').value = "hello"; then add <?php echo $_POST['hiddeninput']; ?> to the run.php page, nothing shows up
0

I believe this is what you are looking for. A way of having the information computed over PHP, without a page request. This uses a form and then serializes the data, then transmits it to PHP and displays the result from run.php.

Note: I did change your id to a name in the HTML so the code would serialize properly. I can change this per request.

index.php

$rand = rand(10,100);

?>

<form action="javascript:void(0);" id="targetForm">
    <input type="hidden" name="idg" value="<?php echo $rand ?>">
    <input type="text" value="12" name="userinput" id="userinput">
    <button onclick="ready()">Go!</button>
</form>

<div id="result"></div>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<script>
function ready() {
    $.post('run.php', $('#targetForm').serialize(), function (data) {
        $("#result").html(data);
    })
}
</script>

run.php

<?php

echo floatval($_POST['userinput']) * floatval($_POST['idg']);

?>

Comments

0

Nowhere in your question is there any indicator that your task requires AJAX. You're just trying to change an input value right when you submit. AJAX is not needed for that.

First, attach an onsubmit event handler to your form instead of using an onclick attribute on your button. Notice, we are not stopping the form from submitting with return false as we still want the form to submit.

For convenience, let's add an ID to your form and let's add a hidden input field to store the calculated value.

(Side-remark: you don't need to use document.getElementById(ID) if the ID is a string with no dashes i.e. document.getElementById('userinput') can be shortened to just userinput )

<form action="/run.php" method="POST" target="_blank" id="theform">
    <input type="hidden" id="idg" value="<?php echo $rand ?>">
    <input type="text" name="userinput" id="userinput">
    <input type="hidden" name="hiddeninput" id="hiddeninput">
    <button type="submit">Go!</button>
</form>

<script>
// this will be called right when you submit
theform.onsubmit = function calcResult() {
    // it should update the value of your hidden field before moving to the next page
    hiddeninput.value = parseInt(userinput.value, 10) + 10;
    return true;
}
</script>

9 Comments

This seems like an ideal solution because it's so simple, but when I add <?php echo $_POST['hiddeninput']; ?> to run.php, nothing shows up (there's no console errors or anything like that either)
I just tested it... You've also added <input type="hidden" name="hiddeninput" id="hiddeninput"> to your form right? Which browser are you using by the way? Maybe try adding return true; in the function as shown in my last edit.
Yeah, I'm not sure if there's a basic error I'm making jsfiddle.net/Pebbley/1s812twg or whether it's because calcResult is no longer being called?
It should be echo $_POST['hiddeninput'];.
That still doesn't work unfortunately. No console errors either.
|
0

One way is by onSubmit

  <form action="/run.php" method="POST" onSubmit="return calcResult()">
    <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>

And when you return true then only form will submit.

<script>
  function calcResult() {
    var userinput = document.getElementById('userinput').value;
    var result = userinput + 10; // want to POST result in a hidden input field w/ form
   return true;
  }
</script>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.