Reputation: 49321
I cant get this form to submit correctly. If I have the button type as "submit" it always submits and if I use "button" as the type it never submits, the ajax call brings in the correct values, so even though the if
statement follows the correct path but it doesnt seem to matter.
<script type="text/javascript">
$(document).ready(function(){
$("#submitButton").click(function(e) {
var un = $('#username').val();
$('#mike').html("");
$.ajax(
{
type: "POST",
url: "Utilities/CheckUsername.php",
data: "un="+ un,
success: function(data2)
{
if(data2=="Username Does Not Exist")
{
$("#login2").submit();
}
else
{
$('#mike').html(data2);
return false;
}
}
});
});
});
</script>
</head>
<body>
<form name="login" id="login2" method="post" action="dsds.html">
UserName<input type="text" name="username" id="username"value="">
<br/>
Password<input type="text" name="password" id="password" value="">
<br/>
Password Again<input type="text" name="passwordagain" id="passwordagain" value="">
<br/>
<input type="hidden" name="NewClass" id="NewClass" value="true">
<br/>
<input type="submit" name="no" id="submitButton" value="submit">
</form>
<span id = "mike"></span>
</body>
</html>
EDIT: I added the return false here and it works, but why? I am just returning false from the click event
else
{
$('#mike').html(data2);
}
}
});
return false;
});
Upvotes: 0
Views: 9562
Reputation: 816262
I suggest you bind the event handler to the submit
event of the form:
$('#login2').submit(function(event) {
event.preventDefault();
//...
});
You have to prevent the default action for the event, which is submitting the form. This is done with event.preventDefault
[docs]. The return false
inside the Ajax callback will have no effect, as the event handler returns before the response was received.
If you do this, you have to set some kind of flag to see in which state of the process you are:
var nameAvailable = false;
$('#login2').submit(function(event) {
if(!nameAvailable) {
event.preventDefault(); // don't submit form
//...
$.ajax({
success: function() {
// if name available
nameAvailable = true;
$('#login2').submit();
}
});
}
});
Upvotes: 2
Reputation: 41802
You just need to return false
from your submit event handler. The return false
you have in there isn't performed until after the asynch ajax call is finished.
Alternatively you can use e.preventDefault()
which does the same thing.
Both methods simply prevent the default behavior, i.e. submitting the form, from occurring.
Upvotes: 3