Stinvurger Stinvurger - 1 year ago 237
Ajax Question

JavaScript AJAX preventDefault

I'm making a simple login page (backed by PHP and MySQL) to learn more about JavaScript and AJAX. I had it working with a form without a submit button, just a button with an onclick method call. However, I want it to be a submit button so hitting enter will call the function, and that seems the proper way to do things anyway. After endless research and trying to translate jQuery solutions, I still can't stop the form from submitting by default.

If I fill out the form with test data and submit, it submits the form with "?username=test&password=test&submit=Log+In" in the url and reloads the page, without displaying the message from the server. Why isn't the event preventDefault working? I've also tried this with adding the eventlistener to the form element with a submit event.

if (isset($_SESSION['user']))
header("Location: home.php");
document.getElementById('login_btn').addEventListener('click', login(event));
var request = new XMLHttpRequest();
function login(evt) {
var username = encodeURIComponent(document.getElementById('username').value);
var password = encodeURIComponent(document.getElementById('password').value);'POST', 'login.php', true);
request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
request.onreadystatechange = process_login;
request.send('username=' + username + '&password=' + password);
function process_login() {
if (request.readyState == 4) {
if (request.status == 200) {
var response = request.responseXML;
var message = response.getElementsByTagName('message').item(0).firstChild.nodeValue;
if (message == '')
window.location = 'home.php';
document.getElementById('message').innerHTML = '<b>' + message + '</b>';
<title>Log In</title>
<h2>Please Log In</h2>
<tr><td>Username:</td><td><input type="text" name="username" id="username"></td></tr>
<tr><td>Password:</td><td><input type="password" name="password" id="password"></td></tr>
<tr><td><input id="login_btn" type="submit" name="submit" value="Log In"></td></tr></form>
<tr><td colspan="2"><div id="message" /></td></tr>

Answer Source
document.getElementById('login_btn').addEventListener('click', login(event));

You are calling login immediately and trying to use its return value (undefined since it has no return statement) as the event handler.

Remove (event) from there.

… at least that is what would happen if you weren't trying to call null.addEventListener. See this question and learn how to use the developer tools for your browser so you can see error messages from JavaScript.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download