I am trying to use ajax jquery concept in my application, which is new to me. I have written out the code. But not getting exact output. My code is like:
<script type="text/javascript" src="js/jquery-1.7.1.min.js"></script>
<form name="ajax" id="ajax" method="post" action="">
Username: <input type="text" name="username" id="username" /><br />
Password: <input type="text" name="pass" id="pass" value="" /><br />
<input type="submit" name="sub_btn" id="sub_btn" value="Login" />
</form>
<script type="text/javascript">
$(document).ready(function(){
$('#sub_btn').click(function(){
var username = $('#username').val();
var password = $('#pass').val();
var datastring = "username="+username+"&password="+password;
$.ajax({
type:"POST",
url: "bin/login-process.php",
data: datastring,
success: function(){
alert("Success");
},
error: function(){
alert("Fail");
}
});
});
});
</script>
and in the bin/login-process.php file I just echo “hello”.
Now if I am trying to run this page,I am getting the alert message(“Fail”) but that is for a very very short time and it again redirects to the same page. But I don’t want to disappear the alert message until user clicks on the “ok” button.
You have two ways to fix this problem.
1. Change the button type to “button”
2. Modify your click handler
Reason:
When you add a submit button to your form, clicking the button trigger a submit event hence submit the form to the provided action, in your case you want to submit your form using Ajax so your should prevent the default behavior by adding event.preventDefault() that means you are preventing default action of the event.
Suggestion:
Instead of hooking click event of the button, hook the submit event of the form, after all people can also submit your form but hitting “Enter” key. This will work for both mouse click and keyboard Enter key.