Вопрос

I have a form in 'index.php`

<form action="" method="POST" id="myForm" name="myForm">
    <input type="text" name="myInput" id="myInput" maxlength="9" onChange="runOnce();" />
</form>

and in my JS code I have:

function runOnce() {
    var form = document.getElementById("myForm");
    form.submit();
}

and I also have the JS to handle the submission

$(document).ready(function() {
    $("#myForm").submit(function(event) {
         // prevent page refresh
         event.preventDefault();
         $.ajax({
             url: 'index.php',
             type: 'post',
             data: {
                 "myInput" : $('#myInput').val(), 
             },
             success: function(response) {
                 alert(response);
             }
         });
    });
});

and in my PHP section I have

if (isset($_POST["myInput"])) {
    // do something. . . 
}

The issue is that the page is still being refreshed even though i have event.preventDefault();

What am I doing wrong?

Это было полезно?

Решение

You could simply use:

function runOnce() {
    $("#myForm").submit(); // this will trigger jQuery submit handler and so preventing default behaviour
}
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top