Bineesh
Bineesh

Reputation: 494

Js edited div content disappears

Hi I'm appending content to the div, after an ajax call success. But quickly the appended text disappears. Why that happens, could you please help?

My js is kept in another file and js is called via a button click event.

HTML:

<html>

  <head> </head>

  <body>
    <script type='text/javascript' src='jq/jquery.js'></script>
    <script type='text/javascript' src='js/bootstrap.min.js'></script>
    <script type='text/javascript' src='js/script.js'></script>
    <br/>

    <form name="form">
        <input type="text" id="uname" name="uname">
        <input type="submit" onclick="postData()" id="data-submit"> 
    </form>

    <br/>
    <br/>
    <br/>
    <br/>

    <div id="feedback"></div>

    <script type='text/javascript'>
      //this sometimes show errors on google chrome. 
      //$(document).ready(function(){});
    </script>
  </body>

</html>

This is the full content of my js file

function postData(){                
    var uname=$('#uname').val();    
    $.ajax({
            url:'checkempcode.php',
            data: {name: uname},
            type: "POST",           
            async: false,
            success: function(data){
                window.alert('Checking');
                $('#feedback').html(data);
                $( "#feedback" ).append( "<p>Test</p>" );
            }
    }); 
}

Upvotes: 3

Views: 144

Answers (2)

Zakaria Acharki
Zakaria Acharki

Reputation: 67525

You should just add event.preventDefault() to you function to prevent form from submiting :

function postData(){              
    event.preventDefault();

    var uname=$('#uname').val();    
    $.ajax({
            url:'checkempcode.php',
            data: {name: uname},
            type: "POST",           
            async: false,
            success: function(data){
                window.alert('Checking');
                $('#feedback').html(data);
                $( "#feedback" ).append( "<p>Test</p>" );
            }
    }); 
}

Hope this helps.

Upvotes: 0

Gilsha
Gilsha

Reputation: 14589

The page get reloaded since the submit buttons are submitting your form. Try changing the button type from submit to button

 <input type="button" onclick="postData()" id="data-submit"/>

OR

Add return false in onclick function;

 <input type="submit" onclick="postData(); return false;" id="data-submit"/>

Upvotes: 2

Related Questions