I am using Ajax with form in Ajax I have used a if condition for validation if my form is empty it should display a message that all fields are required and if fields are fill it should add data in dB and display a success message although everything is working perfectly except one thing which is that my output only display for a second and then automatically disappears can anyone help me in this regard:
`
<html>
<head>
<meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
<title>Document</title>
<script src="jquery.js"></script>
<link rel="stylesheet" type="text/css" href="stylesheet.css">
</head>
<body>
<h1>PHP & Ajax Seralize Form</h1>
<form id="form-data" method="post">
Name<br><input type="text" name="name" id="name" value=""><br><br>
Age<br><input type="number" name="number" id="age" value=""><br><br>
Gender<br>
<input type="radio" name="gender" value="Male">Male
<input type="radio" name="gender" value="Female">Fe-male<br><br>
<select name="country">
<option value="Kashmir">Kashmir</option>
<option value="Egypt">Egypt</option>
<option value="Norway">Norway</option>
<option value="Iceland">Iceland</option>
</select><br>
<br><input type="submit" id="submit" value="Save">
</form>
<div id="response">
</div>
<script>
$(document).ready(function(){
$('#submit').click(function(){
var name = $('#name').val();
var age = $('#age').val();
if( name== "" || age== ""){
$('#response').fadeIn();
$('#response').removeClass('success-msg').addClass('error-msg').html("All fields are required");
}else{
$.ajax({
url: 'save-form.php',
type: 'POST',
data: $('#form-data').serialize(),
success: function(result){
$('#response').fadeIn();
$('#response').removeClass('error-msg').addClass('success-msg').html(result);
}
});
}
});
});
</script>
</body>
</html>
`
probably your page is refreshed, try to use preventDefault to prevent the refresh
$('#submit').click(function(event){
//your code here
event.preventDefault();
}