I am learning to use ajax. By clicking a submit button in a form, does not send data.
Jquery code:
$('input[name="login"]').click(function() {
var username = $('#username').val();
var password = $('#password').val();
$.ajax({
type: 'POST',
url: '/?module=login&special_content=true',
data:{'username':username,'password':password, 'action':'login'},
success: function(e) {
if(e == false)
{
}
else
{
document.location.href = e;
}
}
});
});
HTML code:
<section style="width: 400px; margin: 10% auto; float: none;" id="box">
<section id="box-header">
<div id="box-title">%header_login%</div>
</section>
<section id="box-content" style="float: none;">
<form method="POST" action="./">
%login_username%<br>
<input type="text" style="width: 100%;" class="input" name="username" placeholder="%login_input_user%" required/><br>
%login_password%<br>
<input type="password" style="width: 100%;" class="input" name="password" placeholder="%login_input_pass%" required/><br>
<input type="button" id="login-button" style="width: 100%; box-sizing: border-box;" class="btn btn-red" name="login" value="%login_button%" />
</form>
<center><div style="margin-top: 5px;"> %login_or% <a href="?module=register">%login_signup%</a></div></center>
</section>
Where is the error? Thanks!
Your issue is caused by your selectors. $("#username")
means you want an element with the id
set to "username".
For your two text inputs, change name="username"
and name="password"
to id="username"
and id="password"
respectively.
In your code the #username
and #password
don't exist thus the .val()
returns empty/null.
Change the selector to input[name=
will fix the problem
$('input[name="login"]').click(function() {
var username = $('input[name=username]').val();
var password = $('input[name=password]').val();
$.ajax({
type: 'POST',
url: '/?module=login&special_content=true',
data:{'username':username,'password':password, 'action':'login'},
success: function(e) {
if(e == false)
{
}
else
{
document.location.href = e;
}
}
});
});
check post requests with devtools ass seen in picture