Django JQuery AJAX submit form POST request refreshes the page - javascript

I have a login form for which I want the client to send AJAX POST request as below with error handling. In case of validation/authentication errors, I don't the page to be reloaded or refreshed to the url corresponding to POST request Handler(/users/login/) with the JSON string received from login view's response. I tried using event.preventDefault() as suggested by many answer on SO but could not make it work. Any clue as to what is going wrong here? I don't think this to be a Django issue. I know that the onsubmit is triggerred because the window redirects to the POST handler URL /users/login/ with the expected JSON string response - {"error": ["Entered mobile number is not registered"]}
JQuery code
$("#loginform").on('submit', function(event) {
event.preventDefault();
alert("Was preventDefault() called: " + event.isDefaultPrevented());
console.log("form submitted!");
var url = "/users/login/";
$.ajax({
type: "POST",
url:url,
data: $("#loginform").serialize(),
success: function(data)
{
console.log(data);
var result = JSON.stringify(data);
if(result.indexOf('errors')!=-1 ){
console.log(data);
if(data.errors[0] == "Mobile number and password don't match")
{
$('.login-error').text("Mobile number and password don't match");
}
else if(data.errors[0] == "Entered mobile number is not registered")
{
$('.login-error').text("Entered mobile number is not registered");
}
}
else
{
window.open("/users/profile/");
}
//var result = JSON.stringify(data);
// console.log(result);
}
})
});
View Handler
def login(request):
if request.method == 'POST':
mobile_number = request.POST.get('mobile_number', '')
password = request.POST.get('password', '')
data = {}
user_queryset = User.objects.filter(mobile_number=mobile_number)
if len(user_queryset) == 0:
data['error'] = []
data['error'].append("Entered mobile number is not registered")
# return JsonResponse(data)
elif len(user_queryset) == 1:
email = user_queryset[0].email
user = auth.authenticate(email=email, password=password)
if user is not None:
auth.login(request, user)
else:
data['error'] = []
data['error'].append("Mobile number and password don't match")
return JsonResponse(data)
HTML code
<div class="container-fluid bg-primary" id="login">
<div class="row">
<div class="col-lg-3 text-center">
</div>
<div class="col-lg-6 text-center">
<h1> </h1><h3> </h3>
<h2 class="section-heading">Login to your profile</h2>
<hr>
</div>
<div class="col-lg-3 text-center">
</div>
<h2> </h2>
<h2> </h2>
<h2> </h2>
</div>
<div class="col-md-4 col-md-offset-4 ">
<form id='loginform' action='/users/login/' method='post' accept-charset='UTF-8'>
{% csrf_token %}
<fieldset >
<div class="form-group">
<input type="text" name="mobile_number" id="mobile_number" tabindex="1" class="form-control" placeholder="Mobile Number" value="">
</div>
<div class="form-group">
<input type="password" name="password" id="password" tabindex="2" class="form-control" placeholder="Enter Password">
</div>
</fieldset>
<button type="submit" class="btn btn-primary btn-xl btn-block">LOG IN</button><br><br>
<span class="login-error"></span>
<h1> </h1><h1> </h1>
</form>
</div>
</div>

In addition to event.preventDefault();, it might be a good idea to also call event.stopPropagation() in this case.

Use : 'event.preventDefault()' or 'return false' after the ajax call.

Related

How to loging to django with login form? With or without Ajax

Problem:
If user is loggedin, I want to show greet user else show the form
and when the valid data is submitted, log in the user and
show greet message.
I am trying to pass the data on submit and update the user status to login. I tried with and without ajax but with both ways I could not figure out solution. Could you please help me why its failing? And how I can solve this?
HTML Form:
{% if user.is_authenticated %}
<h5 class="title billing-title ls-10 pt-1 pb-3 mb-0">
Welcome {{ user.username }}!
</h5>
{% else%}
<div class="login-toggle">
Returning customer? <a href="#"
class="show-login font-weight-bold text-uppercase text-dark">Login</a>
</div>
<form class="login-content" name="ajaxLogin" method="POST" action="{% url 'ecommerce:ajaxlogin' %}">
{% csrf_token %}
<p>If you have shopped with us before, please enter your details below.
If you are a new customer, please proceed to the Billing section.</p>
<div class="row">
<div class="col-xs-6">
<div class="form-group">
<label>Username or email *</label>
<input type="text" class="form-control form-control-md" name="username" id="id_email"
required>
</div>
</div>
<div class="col-xs-6">
<div class="form-group">
<label>Password *</label>
<input type="password" class="form-control form-control-md" name="password" id="id_password"
required>
</div>
</div>
</div>
<div class="form-group checkbox">
<input type="checkbox" class="custom-checkbox" id="remember" name="remember">
<label for="remember" class="mb-0 lh-2">Remember me</label>
Lost your password?
</div>
<button class="btn btn-rounded btn-login" type="submit" >Login</button>
</form>
{% endif%}
Views.py :
def ajaxlogin(request):
is_ajax = request.headers.get('X-Requested-With') == 'XMLHttpRequest'
if is_ajax and request.method == "POST":
username = request.POST['username']
password = request.POST['password']
user = authenticate(user=username, password=password)
if User.is_active and not None :
login(request)
else:
pass
return render('./ecommerce/checkout.html')
AJAX:
$(document).ready(function(){
$('.login-content').on('submit', function(event){
event.preventDefault();
var action_url = $(this).attr('action')
$.ajax({
url: action_url,
type:"POST",
data: $('.login-content').serialize(),
headers: { "X-CSRFToken": $.cookie("csrftoken") },
success: function (data) {
console.log("login Successful");
},
});
});
});
Django authenticate takes keyword arguments username and password for the default case with request as optional parameter.
In your views.py you pass user as parameter in authenticate change it to username.
The default authentication returns None if user is in-active so you don't have to check for is_active if you are using default authentication.
Change your views.py as
def ajaxlogin(request):
is_ajax = request.headers.get('X-Requested-With') == 'XMLHttpRequest'
if is_ajax and request.method == "POST":
username = request.POST['username']
password = request.POST['password']
user = authenticate(username=username, password=password)
if user is not None :
login(request, user)
else:
pass
return render('./ecommerce/checkout.html')
Also set contentType as application/x-www-form-urlencoded or leave it at the default by omitting the contentType key.

POST Ajax for multiple buttons in one form

I am creating one form that has Auth and Login buttons that is planned to handle sending out OTP and checking if OTP is valid respectively below.
I am following this Process a Form Submit with Multiple Submit Buttons in Javascript using below code, but when I get any button, javascript seems to be not working and I can't not get any console.log values. No error on the browser.
otplogin.html
<div id="otplogin">
<form class="form-horizontal" id="getotp" >
{% csrf_token %}
<div class="control-group">
<label class="control-label" for="username">Username</label>
<div class="controls">
<input type="text" id="username" name="username" placeholder="Username">
</div>
</div>
<div class="control-group">
<div class="controls">
<button type="submit" value='auth' class="btn">Auth</button>
</div>
</div>
<div class="control-group">
<label class="control-label" for="otp">OTP</label>
<div class="controls">
<input type="otp" name="otp" id="otp" placeholder="OTP">
</div>
</div>
<div class="control-group">
<div class="controls">
<button type="submit" value='login' class="btn">Login</button>
</div>
</div>
</form>
</div>
<script type="text/javascript">
(function () { //the browser said the '$' as in the linked answer can not be recognized
$("#getotp btn").click(function (ev) {
ev.preventDefault()
if ($(this).attr("value") == "auth") {
console.log("CHECK 1");
$.ajax({
type:'POST',
url:'/getotp2',
data:{
username:$('#username').val()
,csrfmiddlewaretoken: $('input[name=csrfmiddlewaretoken]').val()
},
success: function server_response(response) {
console.log('POST1 success')
}
});
}
else if ($(this).attr("value") == "login") {
console.log("CHECK 2");
$.ajax({
type:'POST',
url:'/otplogin',
data:{
username:$('#username').val(),
otp:$('#otp').val(),
csrfmiddlewaretoken: $('input[name=csrfmiddlewaretoken]').val()
},
success: function server_response(response) {
console.log('POST2 success')
}
});
}
});
});
</script>
views.py
def otplogin(request):
if request.POST:
otpentered=request.POST.get('otp','')
if otpentered==otp:
return redirect('/main')
return render(request,'esearch/otplogin.html')
def getotp2(request):
logout(request)
username = otp = ''
if request.POST:
username = request.POST.get('username','')
otp = pyotp.TOTP('base32secret3232').now()
OTPEmail('You Auth',username,[],'Your auth is '+otp)
print ('POST'+username)
print ('POST'+otp)
return JsonResponse(json.dumps({'username':username,'otp':otp}),safe=False)
Appreciate any help on this
Your selection is wrong:
(function(){
$("#getotp btn").click(function (ev){...});}
Change to:
$(document).ready(function(){
$(".btn").click(function(ev){...});});
Or
$("#getotp .control-group .controls .btn").click(...

django encountered with ConnectionResetError: [WinError 10054]

I am new to django and would like to write a simple log in web page
frontend: html, css, javascript(using bootstrap and jquery)
After filling the username and password and clicking the sign in button, it is supposed to jump to the home page.
Here is my code:
html:
<form id="sign-form" role="form">
{% csrf_token %}
<div class="form-group">
<label for="name" class="sr-only"> username </label>
<input id="name" type="text" class="form-control" placeholder="Username...">
</div>
<div class="form-group">
<label for="password" class="sr-only"> password </label>
<input id="password" type="password" class="form-control" placeholder="Password...">
</div>
<div class="form-group">
<button class="btn btn-block" id="sign-in-button"> Sign in </button>
</div>
<div class="form-group">
<button class="btn btn-block" id="sign-up-button"> Sign up </button>
</div>
</form>
js:
$("#sign-in-button").click(function () {
var name=$("#name").val();
var word=$("#password").val();
$.post("/login/",
{
'username': name,
'password': word
},
function (result) {
alert(result);
}
);
});
urls:
urlpatterns = [
path('admin/', admin.site.urls),
path(r'landing/', views.landing_page),
path(r'login/', views.login),
path(r'homepage/', views.home_page),
]
views:
def landing_page(request):
return render(request, "landingPage.html")
def login(request):
print("here log in")
if request.method == 'POST':
username = request.POST.get('username')
password = request.POST.get('password')
user = auth.authenticate(username=username, password=password)
print(username+" out")
if user is not None:
auth.login(request, user)
print(username)
return render(request, "homePage.html", {'username': username})
return render(request, "homePage.html")
return render(request, "homePage.html")
But I encountered this problem(please have a look at the pictures):
The remote host forced the closure of an existing connection
The remote host forced the closure of an existing connection
The remote host forced the closure of an existing connection

Ajax Login Response Error

i'm traying to login with ajax and php, in that situation i'm logging succesfuly actually. But i'm trying to make an alert and refresh the page when logged in.
When i attempt to login, its gives me error and no refreshing. But if i refresh the page, i see i have session in php. I don't understand why.
Here is my code;
<script>
$(document).ready(function(){
$('#login_btn').click(function(){
var email = $('#email').val();
var password = $('#password').val();
if(email == '' || password == ''){
$("#login_error").html("*** Please enter your email / password");
}else{
$('#login_error').html("<strong class='text-success'>Validating...</strong>");
$.ajax({
url: "login.php",
method: "post",
data:{email:email, password:password},
success: function(data){
if (data === 'yes') {
window.location.reload();
}else{
$('#login_error').html("<strong class='text-danger'>ERROR...</strong>");
}
}
});
}
});
});
</script>
login php:
<?php
session_start();
include ('../config/setup.php'); #database connection
if(isset($_POST['email'])){
$q = "SELECT * FROM users WHERE email = '$_POST[email]' AND password = '$_POST[password]'";
$r = mysqli_query($dbc, $q);
if(mysqli_num_rows($r) > 0){
$_SESSION['email'] = $_POST['email'];
echo "yes";
}else{
echo "no";
}
}
?>
Html: (Using login form inside a modal)
<div class="modal-body">
<div class="form-horizontal">
<div class="form-group">
<label for="email" class="col-sm-4 control-label">Email</label>
<div class="col-sm-8">
<input type="email" class="form-control" name="email" id="email" placeholder="Account Email">
</div>
</div>
<div class="form-group">
<label for="password" class="col-sm-4 control-label">Password</label>
<div class="col-sm-8">
<input type="password" class="form-control" name="password" id="password" placeholder="Account Password" >
</div>
</div>
<div class="form-group">
<div class="col-sm-1"></div>
<div align="center" class="col-sm-10">
<button name="login_btn" id="login_btn" class="btn btn-success btn-block text-center"><span id="loader_before" class="glyphicon glyphicon-log-in" aria-hidden="true"></span><i id="loader" class="fa fa-spinner fa-spin fa-x fa-fw"></i> Log in to Account</button>
</div>
<div class="col-sm-1"></div>
</div>
</div>
<div align="center" class="container-fluid">
<h6><strong class="text-danger">Forgot your password? Click here..</strong></h6>
</div>
<h5><div id="login_error" class="text-warning"></div></h5>
</div>
You just need to update your if block in response as below
`
if (data === 'yes') {
alert("You message here!");
window.location.reload();
}else{
$('#login_error').html("<strong class='text-danger'>ERROR...</strong>");
}
`
When you call echo on php, it will write the value, but not return it. That's the problem.
You are not returning "yes" or "no" from login.php, you're just doing echo, which will only write the value but not return it to the caller.
The ajax call is waiting for a response to process it with the 'success' callback. Since login.php is not returning anything, it will always fall into the else clause.
The solution is to change this on login.php
if(mysqli_num_rows($r) > 0){
$_SESSION['email'] = $_POST['email'];
return "yes";
}else{
return "no";
}

Ajax function reloads the page with some parameter on response

I am working on an application where user submit his/her information in tabs...
After .onclick() function, data is submitted to action and saved correctly and returned "success" successfully redirect user to login page...
I have returned two responses so far, "success" and "fail"
But the problem really is, when returning "false"...console.log shows the response correctly, although the work i'd like to perform on "fail" isn't really working..and page reloads with some parameters(i will show it in snapshot)....
Html
<form class="form-horizontal" id="default" name="myform">
<fieldset title="Step1" class="step" id="default-step-0">
<div class="form-group">
<label class="col-lg-2 control-label">Email</label>
<div class="col-lg-10">
<input type="email" class="form-control" id="Email1" required>
<label id="err1" class="col-lg-6 control-label" "></label>
</div>
</div>
<div class="form-group">
<label class="col-lg-2 control-label">Password</label>
<div class="col-lg-10">
<input type="password" name="password1" class="form-control" id="password1" required>
</div>
</div>
<div class="form-group">
<label class="col-lg-2 control-label">Confirm Password</label>
<div class="col-lg-10">
<input type="password" name="confirmpassword1" class="form-control" id="confirmpassword1" required>
<label id="passMatch" class="col-lg-6 control-label""></label>
</div>
</div>
</fieldset>
<fieldset title="Step 2" class="step" id="default-step-1">
//some other input fields on 2nd tab
</fieldset>
<input type="button" class="finish btn btn-danger" value="Save" id="btnSubmitAll" />
</form>
Ajax
<script>
$("#btnSubmitAll").click(function (event) {
event.preventDefault();
var Email = $('#Email1').val();
var password = $('#password1').val();
var confirmpassword = $('#confirmpassword1').val();
$.ajax({
type: "POST",
url: '#Url.Action("Submit", "Home")',
dataType: "JSon",
async: false,
data: {"Email": Email, "password": password, "confirmpassword": confirmpassword},
success: function (data) {
if (data == "success")
{
window.location.href = '#Url.Action("login","Home")';
console.log(data);
}
else {
$('#err1').html("Email Exist");
console.log(data);
}
},
error: function (data, jqXHR, exception) {
//some errors in if/else if/else
}
}
});
});
</script>
Please remember, when data == "success", all things go right(returns success after successfull record insertion), but when "fail" returned, console shows it correctly but label not updated with the message and also the whole page reloads with some parameters from the form inputs as can be seen below...
InAction
if (objIdHelper.IsUserExist(Email))
{
return this.Json ("fail");
}
else
{
//some process
return this.Json ("success");
}
I am surely missing some logic or doing something stupid, please help....
Any kind of help will be appreciated...thanks for your time
Check for the argumet passed in the success callback..Also note that you have wrong understanding for error callback. It wont execute if there are any errors in success callback conditions. It is to handle network errors.
Your if statement if (data == "success") uses data instead of data1 like the function specifies.

Categories

Resources