Abhijith P Haridas
Abhijith P Haridas

Reputation: 135

jquery automatically refresh page

I am trying to load content of a file to a division using jquery. After loading contents the page refresh automatically.

<html>
    <head>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
        <script type="text/javascript">
            $(document).ready(function(){
                $("#btn1").click(function(){
                    $("#div1").load("file.txt");
                });
            });
        </script>
    </head>
    <body>
        <form name='form1'>

            <input id="btn1" type="submit">
        </form>
        <div id="div1"></div>
    </body>
</html>

So the contents in division with id div1 never show up. I put break points to check whether file loads or not. It load successfully. Because of page refresh automatically the contents never displays.

Help me to fix it

Upvotes: 1

Views: 820

Answers (3)

Gonzalo.-
Gonzalo.-

Reputation: 12672

That is because you have a button inside your form

add a e.preventDefault(); and you should be fine

$("#btn1").click(function(e){
      $("#div1").load("file.txt");
      e.preventDefault();
});

the other way would be change your html and make your input as

type="button" instead of type="submit"

The submit button inside a button will trigger a submit when clicked, which is causing your page to reload

Upvotes: 0

giorgio
giorgio

Reputation: 10202

That because you have put the button inside a form without an action attribute, which then defaults to the page itself. So basically what happens is that it is loading the contents of your file and then posting a form to itself, which causes the refresh.

Why do you need a form anyway? Change the button to <button id="btn1">Click here to load</button> and place it outside of the form. Or change the function to:

$(document).ready(function(){
    $("#btn1").click(function(e){ // e is the event object
        e.preventDefault(); // this prevents the form from posting.
        $("#div1").load("file.txt");
    });
});

Upvotes: 0

Sushanth --
Sushanth --

Reputation: 55740

Prevent the default action of the submit button.

$("#btn1").click(function(e){
    e.preventDefault();
    $("#div1").load("file.txt");
});

Upvotes: 4

Related Questions