1

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

1
  • I would go with type='button'..Simple! Commented Nov 2, 2015 at 18:45

3 Answers 3

4

Prevent the default action of the submit button.

$("#btn1").click(function(e){
    e.preventDefault();
    $("#div1").load("file.txt");
});
Sign up to request clarification or add additional context in comments.

1 Comment

@AbhijithPHaridas . Glad to have helped.
0

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");
    });
});

Comments

0

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

1 Comment

That won't work, you forgot the e inside function parameters $("#btn1").click(function(e){

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.