Sebastian Dine Sebastian Dine - 6 months ago 24
Javascript Question

jQuery $.post-function | data-processing function does not work

I am new in web development, but having years of experience in traditional development, e.g. using Java, C and ABAP, under my belt.

I am trying to create a pretty simple Login-functionality, but struggling with jQuery's

$.post()
-functionality.

In the below seen code, the
alert("test")
-function in the data-processing part of
$.post()
doesn´t seem to get executed, after I submit the form
form_login
. I guess the problem is with how I connected the JavaScript-function
login_attempt()
with the submitting of form
form_login
.



<!DOCTYPE html>
<html>
<head>
<title>Login</title>

<script src="jquery-2.2.4.min.js"></script>

<script>
function login_attempt(){
$.post("login.php", $("#form_login").serialize(), function(data){alert("test");},html);
}
</script>

</head>
<body>
<h1>Login-Form</h1>
<form id="form_login" method="post" onsubmit="return login_attempt()">
<p><label for="id_username">Username: </label><input id="id_username" name="username" type="text" width="20"></label></p>
<p><label for="id_password">Password: </label><input id="id_password" name="password" type="password" width="10"></label></p>
<p><input type="submit" name="submit_login"></p>
</form>


</body>
</html>




Answer

The function login_attempt is now triggered when submitting the form and then after that the form is submitted as well since the login_attempt function does not tell the form to stop submitting in the regular way. Therefor the page reloads before the actual callback of the post method could do anything.

Add return false; as last line of the login_attempt function to tell the form it should not submit in the regular way.

Comments