user1434156
user1434156

Reputation:

JS/AJAX: Submit form with timer and not a button click or refresh of page

I am trying to submit a form without page refresh or a submit button. But i have only achieved to have the JS function submit the input box value. Is it possible to submit the whole form without a button click and refresh of page?

JSFIDDLE

JS

            <script type="text/javascript">
                $(document).ready(function() {
                    var timer;
                        $('#yurl).on('keyup', function() {
                            var value = this.value;

                            clearTimeout(timer);

                            timer = setTimeout(function() {

                                //do your submit here

                                alert('submitted:' + value);
                            }, 2000);
                        });
                });
            </script>

html

                <form method="post" id="ytVideo" action="">
                <input id="yurl" type="text" value="<?php $url ?>" name="yurl">     
                </form>

Upvotes: 1

Views: 1570

Answers (3)

Wern Ancheta
Wern Ancheta

Reputation: 23297

Your fiddle seems to be working but the problem is that you're not really submitting it anywhere.

<script type="text/javascript">
 $(document).ready(function() {
                        var timer;
                            $('#yurl).on('keyup', function() {
                                var value = this.value;

                                clearTimeout(timer);

                                timer = setTimeout(function() {

                                    //do your submit here
                                    $("#ytVideo").submit()
                                    alert('submitted:' + value);
                                }, 2000);
                            });


     //then include your submit definition. What you want to do once submit is executed
      $('#ytVideo').submit(function(e){
           e.preventDefault(); //prevent page refresh
           var form = $('#ytVideo').serialize();
           //submit.php is the page where you submit your form
           $.post('submit.php', form, function(data){ 
              //do something with the data

           });
      });

});
</script>

Upvotes: 0

ryuusenshi
ryuusenshi

Reputation: 1986

If I understood well what you're asking, where it says //do your submit here you should put:

 $("#ytVideo").submit()

where ytVideo is the id of the form you're trying to submit

Good luck!

Upvotes: 1

Haroldo_OK
Haroldo_OK

Reputation: 7230

I think jQuery.serialize() could solve your problem quite nicely.

Upvotes: 0

Related Questions