Search code examples
jqueryajaxformssubmitdelay

jquery ajax delay form submit


I have this jquery ajax code that submits my form if it gets changed. My only problem is that I also have a country jquery selection in my form and everytime i click on the autocomplete suggestion the form with the old/last value get's submitted. Example: I search for "Austria" and click on it and an empty value gets submitted. Then I change it to "Poland" and "at" for Austria is submitted. My idea is to delay the ajax call: $.ajax but I couldn't find out how.

<script type="text/javascript">
$(document).ready(
function submitFormAjax()
{
    $('#myForm').change(function() {
        $.ajax({
            type:"POST",
            url:"ajax.php",
            data:$(this).serialize(),
            success:function(data)
            {
                $("#ajaxList").html(data);

            }
        })

      return false;
    });
});
</script>

Solution

  • Not sure if it will work, hard to tell without seeing more of the code, but here's how to delay the $.ajax !

    $('#myForm').on('change', function() {
       setTimeout(submitFormAjax, 200);
       return false;
    });
    function submitFormAjax() {
        $.ajax({
            type:"POST",
            url:"ajax.php",
            data:$('#myForm').serialize(),
            success:function(data) {
                $("#ajaxList").html(data);
            }
        });
    }