ledesma
ledesma

Reputation: 378

JQuery AJAX auto submit form

Im trying to post a form with ajax and its working fine... but when i try to put to auto submit the form its not workin... If i press the submit button.. its fine.. but if i setInterval("submitform();", 5000); ajax doesnt work (i mean it reloads the page).

ajax.js

$(document).ready(function(){
    $('#form1').submit(function(){
        $.ajax({
            url : 'inserir.php',
            type : 'POST',
            data : $('form').serialize(),
            success: function(data){
                $('#resultado').html(data);
            }
        });
        return false;
    });
})

form.html

<html>
<head>
    <script type="text/javascript" src="ajax.js" ></script>
</head>
<body>
<form id="form1" method="POST">
    Código: <br />
    <input type="text" name="idVeiculo" id="idVeiculo" value="1"/>
    <br /><br />
    Nome: <br />
    <input type="text" name="nome" id="nome" /><input type="submit">
</form>

<div id="resultado"></div>
 <script type="text/javascript">

    window.onload=function(){
    setInterval("submitform();", 5000);
    }
    function submitform(){ document.getElementById('form1').submit(); }

</script>
</body>
</html>

So if i press the button, it works fine... If i use that auto submit function, reloads the page rather than just post the data to the php file.

Thanks for any help!!

Upvotes: 1

Views: 22237

Answers (1)

Musa
Musa

Reputation: 97672

From MDN

https://developer.mozilla.org/en-US/docs/Web/API/HTMLFormElement.submit

The form's onsubmit event handler (for example, onsubmit="return false;") will not be triggered when invoking this method from Gecko-based applications. In general, it is not guaranteed to be invoked by HTML user agents.

You should separate the ajax call into a function and just call it in the timeout function

$(document).ready(function(){
    $('#form1').submit(ajax);
})
function ajax(){
        $.ajax({
            url : 'inserir.php',
            type : 'POST',
            data : $('form').serialize(),
            success: function(data){
                $('#resultado').html(data);
            }
        });
        return false;
}
...
window.onload=function(){
    setInterval(ajax, 5000);
}

Upvotes: 5

Related Questions