1

I am currently using js function to submit data without page refresh or button click. The input field is inside tab #2 that executes the js once the user stops typing. The problem is that the js is making the page refresh thus taking me back to tab#1. How can I prevent the page from refreshing? I thought i had included the necessary code in the JS function to stop this. EXAMPLE

<script>
$(document).ready(function() {
    var timer;
        $('#video-input1').on('keyup', function() {
            var value = this.value;

            clearTimeout(timer);

            timer = setTimeout(function() {

                //do your submit here
                $("#ytVideo").submit()


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

    //submit definition 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('index.php#tab-2', form, function(data){ 
            var x = $(data);
            $("body").html(x);
        });
        return false;
    });
    return false;                                                         

});
</script>
Elen
  • 2,345
  • 3
  • 24
  • 47
  • The `$("#ytVideo").submit()` line is the problem. Your submitting the form, before it gets to your `$('#ytVideo').submit(function(e){` event where you disable the default behavior and return false. – Jeemusu Jul 13 '12 at 16:53
  • Thank you for responding, how could i fix such problem? –  Jul 13 '12 at 17:18

2 Answers2

1

try changing this line

//do your submit here
$("#ytVideo").submit()

to

$("#ytVideo").trigger("submit");

i believe the problem is that you define what submit should do after the form has been submitted this causes the page to reload.
Edited
try this change

$('#ytVideo').submit(function(event){
        event.preventDefault(); //prevent page refresh
        event.stopPropagation(); //+
        var form = $('#ytVideo').serialize();

        //submit.php is the page where you submit your form
        $.post('index.php#tab-2', form, function(data){ 
            var x = $(data);
            $("body").html(x);
        });
        //- return false;
    });
    //- return false;  

made some changes

Gntem
  • 6,949
  • 2
  • 35
  • 48
  • +1 Yes, I did what you said but it seems to refresh the page taking me back to tab-1 –  Jul 13 '12 at 17:20
  • made some changes, also you make $("body").html(x) <- this replaces all body HTML, hope that script tag with jquery code isn't in there because it will be replaced! – Gntem Jul 13 '12 at 19:03
0

Instead of .submit() you should use .triggerHandler('submit'). Docs and related question.

Community
  • 1
  • 1
jbabey
  • 45,965
  • 12
  • 71
  • 94