When i click my login button, it just reloads the page for some reason. it should alert the string i echo from my php page.
This is my login.js code:
$(document).ready(function(){
$('#login').click(function(){
$('#msgLoginStatus').show();
$('#msgLoginStatus').html("processing...");
$.post('login.php',{username:"bob",password:"pass"}, function(data){
alert(data);
});
});
});
my login.php:
<?php
echo "message";
?>
and my form:
<form id="loginForm" action="" method="post">
<fieldset id="body">
<fieldset>
<label for="username">Username</label>
<input type="text" name="username" id="username" />
</fieldset>
<fieldset>
<label for="password">Password</label>
<input type="password" name="password" id="password" />
</fieldset>
<button id="login">login</button>
<label for="checkbox"><input type="checkbox" id="checkbox" />Remember me</label>
<br />
<p id="msgLoginStatus" style="display:none"></p>
</fieldset>
<span><a href="#">Forgot your password?</a></span>
</form>
There are no errors in browser console. I tried this also using $.ajax, it returned an error, i tried putting the error variable in an alert, but when it alerted, it was an empty string. Anyone have an idea whats wrong?
Your login button has an ambiguous action – add
type="submit"like this:Now if you really want to execute an explicit POST with JavaScript, call e.preventDefault so the browser’s automatic “submit” action will be suppressed.
But it will probably be better to let the form submit itself. To do this specify the correct
action="login.php"attribute in the form:Keep your existing “click” handler on the login button, just remove the “$.post” part and let the browser handle the posting. You’ll still get the nice “processing…” text.
Even better, handle the “submit” event on the form instead of the “click” event on the button:
This way you’ll get the nice updates whether the user submits the form using the button or by pressing “enter” on the keyboard.