PHP $_POST is empty after using jquery val() on in

2019-07-14 01:50发布

I want to check value of input for year of birth. I have figured out that if I use jquery function val() to get value of this input, so the php post of this input will be empty. It works fine without using val(). Here you can see the important part part of code. It is not so essential ability of form, but it would be useful to check if the isn't written anything inappropriate or any mistype.

Thank you for help.

<?php
if (!empty($_POST['rn']) && isset($_POST['rn'])){
    // proceed
} else {
    echo "You haven't filled all inputs";
}
?>
<script>
$("#kontrolaButton").click(function(){
    var rok = parseInt($("#rok_nar").val(),10);
    if (rok > 1900 && rok < 2016) {
        $("#odeslatButton").trigger('click');
    };
});
</script>
<form accept-charset="utf-8" method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" class="send_form">

<input class="bold" id="rok_nar" type="text" name="rn" placeholder="Rok narození"/>
<input type="button" value="Odeslat" name="kontrola" id="kontrolaButton" /> 
<input type="submit" value="Odeslat" name="odeslat" id="odeslatButton" style="visibility: hidden;" />

</form>

Update: I have probably found the problem. I didn't write it here, because I didn't consider it as an issue. My script looks like:

$("#kontrolaButton").click(function(){
    var rok = parseInt($("#rok_nar").val(),10);
    alert(rok);
    if (rok > 1900 && rok < 2016) {
        $("#odeslatButton").trigger('click');
    };
});

After erasing the alert, the code works :/ Interesting...

2条回答
啃猪蹄的小仙女
2楼-- · 2019-07-14 01:58

It looks like your trying to access an input in the dom before it is loaded. I don't see a document ready. You need to either stick your script inside a document ready so it is delayed until the dom is completely parsed, or move your logic at the bottom of your page so the elements exist by the time you try to look them up.

查看更多
淡お忘
3楼-- · 2019-07-14 02:22

You should move the script right to the end of the HTML body so that it executes when the kontrolaButton element is in the DOM.

Note that the mouse down/up or key press/release you issue to close the alert(rok); may interfere with the submission of the form. For instance, I could reproduce a problem like this: I pressed the ESC key to close the alert, and although the form submitted its data, the next page did not render; it was just a blank page. This may be very browser dependent, but on my set-up the ESC key apparently interrupts the rendering of a page.

There may be other such side effects, certainly also if you have other Javascript code on the page that responds to these key or mouse events.

查看更多
登录 后发表回答