What makes the front-end validation of form fail? - javascript

I am working on submitting a form via jQuery AJAX. The form also has basic validation, that I am doing myself.
The HTML (index.html file):
<div class="modal fade" id="exampleModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
<form action="/process" class="modal-dialog" id="order_form">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel">Pre-order</h5>
<button type="submit" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<div id="#validation" class="d-none alert alert-danger">
All fields are mandatory
</div>
<div id="#status" class="d-none alert alert-dismissible">
×
<p class="m-0"></p>
</div>
<div class="form-group">
<label for="first_name">First name:</label>
<input type="first_name" class="form-control" id="first_name" placeholder="First name" name="first_name">
</div>
<div class="form-group">
<label for="last_name">Last name:</label>
<input type="last_name" class="form-control" id="last_name" placeholder="Last name" name="last_name">
</div>
<div class="form-group">
<label for="email">Email address:</label>
<input type="email" class="form-control" placeholder="Enter email" id="email">
</div>
</div>
<div class="modal-footer">
<button type="submit" class="btn btn-primary btn-sm btn-block">Send</button>
</div>
</div>
</form>
</div>
The script:
function isEmail(mail){
return /^(([^<>()\[\]\.,;:\s#\"]+(\.[^<>()\[\]\.,;:\s#\"]+)*)|(\".+\"))#(([^<>()\.,;\s#\"]+\.{0,1})+([^<>()\.,;:\s#\"]{2,}|[\d\.]+))$/.test(mail);
}
function submitOrder(e) {
e.preventDefault();
var form = $(this),
submitUrl = form.attr('action'),
firstName = $('#first_name').val(),
lastName = $('#last_name').val(),
emailAddress = $('#email').val()
// Are there any empty fields?
isEmpty = firstName == ''
|| lastName == ''
|| emailAddress == '';
console.log('Empty filds: ', isEmpty);
console.log('Valid email: ', isEmail(emailAddress));
if (isEmpty) {
$('#validation').removeClass('d-none');
} else {
if (!isEmail(emailAddress)) {
$('#validation').removeClass('d-none').text('Choose a valid email');
} else {
$('#validation').addClass('d-none');
$.ajax({
type: "POST",
url: submitUrl,
data: form.serialize(),
dataType: "json",
success: function(response) {
if (response == 'successful') {
$('#status').addClass('alert-success').find('p').text("Your order was send");
}
else {
$('#status').addClass('alert-danger').find('p').text("We've failed to send your order");
}
$('#status').removeClass('d-none');
}
});
}
}
}
$(document).ready(function(){
// Submit Order Form
$('#order_form').on('submit', submitOrder);
});
The problem:
Evan though the form is not valid, and the console shows Empty filds: true and Valid email: false, the calass 'd-none' is not removed from <div id="#validation" class="d-none alert alert-danger"> and the alert, of course, is not displayed.
What is my mistake?

I've found a mistake in your code but I don't know if it will resolve your problem:
if (isEmpty) {
$(' #validation').removeClass('d-none');
}
should be (space before #validation)
if (isEmpty) {
$('#validation').removeClass('d-none');
}

Here is what worked for me, in case it might help others:
function isEmail(mail){
return /^(([^<>()\[\]\.,;:\s#\"]+(\.[^<>()\[\]\.,;:\s#\"]+)*)|(\".+\"))#(([^<>()\.,;\s#\"]+\.{0,1})+([^<>()\.,;:\s#\"]{2,}|[\d\.]+))$/.test(mail);
}
function submitOrder(e) {
e.preventDefault();
var form = $(this),
submitUrl = form.attr('action'),
firstName = $('#first_name').val(),
lastName = $('#last_name').val(),
emailAddress = $('#email').val()
// Are there any empty fields?
isEmpty = firstName == ''
|| lastName == ''
|| emailAddress == '';
if (isEmpty) {
$('#validation').removeClass('d-none');
} else {
if (!isEmail(emailAddress)) {
$('#validation').removeClass('d-none').text('Choose a valid email');
} else {
$('#validation').addClass('d-none');
var req = $.ajax({
url: form.attr('action'),
type: 'POST',
data: form.serialize()
});
req.done(function(data) {
if (data == 'success') {
$('#status').addClass('alert-success').find('p').text("Your order was send");
}
else {
$('#status').addClass('alert-danger').find('p').text("We've failed to send your order");
}
$('#status').removeClass('d-none');
});
}
}
}
$(document).ready(function(){
// Submit Order Form
$('#order_form').on('submit', submitOrder);
});

Related

Cannot submit form with the usage of Ajax in ASP.NET MVC

I have an issue about submitting a form via ajax and open a modal Dialog after the ajax function is completed successfully. When I click a submitButton, the process cannot be completed.
Where is the problem in an ajax method or anywhere?
How can I fix it?
Here is my form HTML part.
<form id="contactForm" role="form" class="php-email-form">
#Html.AntiForgeryToken()
<div class="row">
<div class="col-md-6 form-group">
<input type="text" name="nameSurname" class="form-control" id="nameSurname" placeholder="Name Surname" required>
</div>
<div class="col-md-6 form-group mt-3 mt-md-0">
<input type="email" class="form-control" name="email" id="email" placeholder="Email" required>
</div>
</div>
<div class="form-group mt-3">
<input type="text" class="form-control" name="subject" id="subject" placeholder="Subject" required>
</div>
<div class="form-group mt-3">
<textarea class="form-control" name="message" id="message" rows="5" placeholder="Message" required></textarea>
</div>
<div class="my-3"></div>
<div class="text-center">
<button type="submit" id="submitButton" data-bs-toggle="modal">Submit</button> <!-- data-bs-target="#modalDialog"-->
</div>
</form>
Here is my modal part.
<div class="modal fade" id="modalDialog" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel">Modal title</h5>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<div class="modal-body">
#ViewBag.Success
</div>
<div class="modal-footer">
<button type="button" class="btn btn-danger" data-bs-dismiss="modal">Kapat</button>
</div>
</div>
</div>
</div>
Here is my javascript part.
<script type="text/javascript">
$(document).ready(function () {
$("#submitButton").click(function () {
var nameSurname = $("#nameSurname").val();
var email = $("#email").val();
var subject = $("#subject").val();
var message = $("#message").val();
var form = $('#contactForm');
var token = $('input[name="__RequestVerificationToken"]', form).val();
$.ajax({
url: '/Home/Contract/',
data: {
__RequestVerificationToken: token,
nameSurname: nameSurname, email: email, subject: subject, message: message
},
type: 'POST',
success: function (data) {
$("#modalDialog").show();
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert('custom message. Error: ' + errorThrown);
}
});
});
})
</script>
Here is my Contract action in Home Controller
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Contract(string nameSurname = null, string email = null, string subject = null, string message = null)
{
if (nameSurname != null && email != null)
{
SmtpClient smtpClient = new SmtpClient("smtp.gmail.com");
smtpClient.Port = 587;
smtpClient.Credentials = new System.Net.NetworkCredential("gmail address", "gmail address password");
// smtpClient.UseDefaultCredentials = true; // uncomment if you don't want to use the network credentials
smtpClient.DeliveryMethod = SmtpDeliveryMethod.Network;
smtpClient.EnableSsl = true;
MailMessage mail = new MailMessage();
mail.Subject = subject;
mail.IsBodyHtml = true;
mail.Body = message;
//Setting From , To and CC
mail.From = new MailAddress(email);
mail.To.Add(new MailAddress("gmail address"));
smtpClient.Send(mail);
ViewBag.Success = "Success";
}
else
{
ViewBag.Error = "Error";
}
return View();
}
EDIT
After I realized Ok() isn’t accessible in an MVC controller I found this solution which does essentially the same thing.
In your controller, change:
return RedirectToAction(“contract”);
To:
return new HttpStatusCodeResult(HttpStatusCode.OK);
RedirectToAction() and View() will by default load or refresh a page while a 200 (OK) response will just return a success status code.
You can do it this way:
View:
#using (Ajax.BeginForm("Contract", "ControllerName", FormMethod.Post, new AjaxOptions { HttpMethod = "POST", OnBegin = "OnBegin", OnSuccess = "OnSuccess", OnFailure = "OnFailure" }, new { #id = "ajaxForm" }))
{
<div class="card">
<div class="card-body">
#Html.AntiForgeryToken()
<div class="row">
<div class="col-md-6 form-group">
<input type="text" name="nameSurname" class="form-control" id="nameSurname" placeholder="Name Surname" required>
</div>
<div class="col-md-6 form-group mt-3 mt-md-0">
<input type="email" class="form-control" name="email" id="email" placeholder="Email" required>
</div>
</div>
<div class="form-group mt-3">
<input type="text" class="form-control" name="subject" id="subject" placeholder="Subject" required>
</div>
<div class="form-group mt-3">
<textarea class="form-control" name="message" id="message" rows="5" placeholder="Message" required></textarea>
</div>
<div class="my-3"></div>
<div class="text-center">
<button type="submit" id="submitButton">Submit</button> <!-- data-bs-target="#modalDialog"-->
</div>
</div>
</div>
}
Controller
[HttpPost]
[ValidateAntiForgeryToken]
public JsonResult Contract(string nameSurname = null, string email = null, string subject = null, string message = null)
{
// do what is necessary
if (nameSurname != null && email != null)
{
SmtpClient smtpClient = new SmtpClient("smtp.gmail.com");
smtpClient.Port = 587;
smtpClient.Credentials = new System.Net.NetworkCredential("gmail address", "gmail address password");
// smtpClient.UseDefaultCredentials = true; // uncomment if you don't want to use the network credentials
smtpClient.DeliveryMethod = SmtpDeliveryMethod.Network;
smtpClient.EnableSsl = true;
MailMessage mail = new MailMessage();
mail.Subject = subject;
mail.IsBodyHtml = true;
mail.Body = message;
//Setting From , To and CC
mail.From = new MailAddress(email);
mail.To.Add(new MailAddress("gmail address"));
smtpClient.Send(mail)
return Json("Success", JsonRequestBehavior.AllowGet);
}
else // return result
{
return Json("Error", JsonRequestBehavior.AllowGet);
}
}
We have to create OnSuccess function in view to do something with result;
<script>
function OnSuccess(data) {
if (data == 'Success') {
$("#modalDialog").modal('show');
}
}
function OnFailure(data) {
//log failure
}
function OnBegin() {
// do something on begin
}
</script>

How to send ID of a row throught submit form / button?

I'm writing a code for the system administrator to be able to reset the users' passwords in their accounts in case they forget said password.
I'm currently having problems passing the target user's ID through Ajax to change said user's password, through debugging tool, the system returns an "undefined" response for "id:", although the "_token" and "password" fields were sent fine.
HTML code for the form
<form id="form-reset-password">
<div class="container my-2">
<div class="row">
<div class="col-md-12">
<div class="form-row">
<input type="hidden" id="token" name="_token" value="{{csrf_token()}}">
</div>
<div class="form-group">
<label>New Password</label>
<input type="text" class="form-control" id="reset-password" name="password" readonly>
</div>
<div class="form-group text-right mt-4">
<button type="button" class="btn btn-dark" data-dismiss="modal">Close</button>
<button type="submit" class="btn btn-success btn-confirmreset">Reset</button>
</div>
</div>
</div>
</div>
</form>
Javascript for generating the data-table where it shows the list of User accounts. On the side of the table, the admin can click a button to reset the password of said user.
$(document).ready(function() {
getRoles();
var accounts;
$('#account-management').addClass('active');
accounts = $("#table-accounts").DataTable({
ajax: {
url: "/users/get-all-users",
dataSrc: ''
},
responsive:true,
"order": [[ 7, "desc" ]],
columns: [
{ data: 'id'},
{ data: 'organization_name', defaultContent: 'n/a' },
{ data: 'first_name' },
{ data: 'last_name' },
{ data: 'email'},
{ data: 'student_number'},
{ data: 'role.name'},
{ data: 'created_at'},
{ data: null,
render: function ( data, type, row ) {
var html = "";
if (data.status == 1) {
html += '<span class="switch switch-sm"> <input type="checkbox" class="switch btn-change-status" id="'+data.id+'" data-id="'+data.id+'" data-status="'+data.status+'" checked> <label for="'+data.id+'"></label></span>';
} else {
html += '<span class="switch switch-sm"> <input type="checkbox" class="switch btn-change-status" id="'+data.id+'" data-id="'+data.id+'" data-status="'+data.status+'"> <label for="'+data.id+'"></label></span>';
}
html += "<button type='button' class='btn btn-primary btn-sm btn-edit-account mr-2' data-id='"+data.id+"' data-account='"+data.id+"'>Edit</button>";
html += "<button type='button' class='btn btn-secondary btn-sm btn-reset-password' data-id='"+data.id+"' data-account='"+data.id+"'><i class='fas fa-key'></i></button>";
return html;
}
},
],
columnDefs: [
{ className: "hidden", "targets": [0]},
{ "orderable": false, "targets": 7 }
]
});
Javascript for the random password generator and reset password
function resetPassword() {
$.ajax({
type: 'GET',
url: '/user/get-new-password',
processData: false,
success: function(data) {
$('#reset-password').val(data.password);
}
});
}
$(document).on('click', '.btn-reset-password', function() {
$('#reset-password-modal').modal('show');
resetPassword();
});
$(document).on('submit', '#form-reset-password', function() {
var confirm_alert = confirm("Are you sure you want to reset this account's password?");
if (confirm_alert == true) {
// var id = $(this).attr('data-id');
var id = $('.btn-confirmreset').attr('data-id');
$.ajax({
url: "/auth/reset-password",
type: "POST",
data: $(this).serialize()+"&id="+id,
success: function(data) {
if (data.success === true) {
alert("Password successfully reset!");
location.reload();
}
else {
alert("Something went wrong");
}
}
});
return false;
}
});
Thank you for your help!
<form id="form-reset-password">
<div class="container my-2">
<div class="row">
<div class="col-md-12">
<div class="form-row">
<input type="hidden" id="token" name="_token" value="{{csrf_token()}}">
<input type="hidden" id="user_id" name="user_id" value=""> // initiate the hidden input here
</div>
<div class="form-group">
<label>New Password</label>
<input type="text" class="form-control" id="reset-password" name="password" readonly>
</div>
<div class="form-group text-right mt-4">
<button type="button" class="btn btn-dark" data-dismiss="modal">Close</button>
<button type="submit" class="btn btn-success btn-confirmreset">Reset</button>
</div>
</div>
</div>
</div>
</form>
<script type="text/javascript">
$(document).on('click', '.btn-reset-password', function() {
var user_id_value = $(this).attr('data-id'); // Get the user id from attr
$('#user_id').val(user_id_value); // Assign the user id to hidden field.
$('#reset-password-modal').modal('show');
resetPassword();
});
$(document).on('submit', '#form-reset-password', function() {
var confirm_alert = confirm("Are you sure you want to reset this account's password?");
if (confirm_alert == true) {
// var id = $(this).attr('data-id');
//var id = $('.btn-confirmreset').attr('data-id'); // Remove this, it won't work , because this button doesn't contain the data-id
var id = $('#user_id').val(user_id_value); // You can get the value from hidden field
$.ajax({
url: "/auth/reset-password",
type: "POST",
data: $(this).serialize()+"&id="+id,
success: function(data) {
if (data.success === true) {
alert("Password successfully reset!");
location.reload();
}
else {
alert("Something went wrong");
}
}
});
return false;
}
});
</script>
Please refer the above code, You can pass the user id while modal pop up call and set that id to hidden value. then you can access that id from the hidden input. when you submit "form-reset-password" form.
Please look at comments on the above code
Maybe the attr() function is looking for native HTML attribute. So use the following snippet will help.
var id = $('.btn-confirmreset').data('id');

Submit change password form in bootstrap modal through ajax

I Have a change password form which I have tried to code so that it gets submitted through ajax.
I needed to do validation too.
Below is the code that I've written. Is there anyway so that we can use this js ajax function for multiple modal forms?
Or will we need to create a seperate function for submitting each modal form?
Also I wanted to make the parent page reload after user closes the modal so I have added this code:
$('#edit').on('hidden.bs.modal', function() {
location.reload();
});
but it reloads the page when someone clicks cancel button too. Is there any way to prevent reloading when clicking cancel button and only do reloading only by clicking "x".
Here is the code
index.php file where the modal is
<p data-placement="top" data-toggle="tooltip" title="Edit" data-original-title="Edit">
<button class="btn btn-primary btn-xs" data-title="Edit" data-toggle="modal" data-target="#edit" data-backdrop="static" data-keyboard="false">
<span class="glyphicon glyphicon-pencil"> Edit</span>
</button>
</p>
<div class="modal fade" id="edit" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title" id="myModalLabel">Edit Your Detail</h4>
</div>
<!--/.modal-header-->
<div class="modal-body">
<form method="post" id="updateForm" action="update-info.php">
<input type="hidden" name="userID" value="<?php echo $_SESSION['user']; ?>" />
<div class="form-group">
<label for="customer_name">Customer Name :</label>
<input class="form-control" type="text" name="customer_name" id="customer_name" value="<?php echo $userRow['fullName']; ?>" />
</div>
<h4><u><strong>Change Password</strong></u></h4>
<div class="form-group" id="currentPass-group">
<label for="current_pass">Current Password :</label>
<input class="form-control" type="password" name="current_pass" id="current_pass">
</div>
<div class="form-group">
<label for="new_pass">New Password :</label>
<input class="form-control" type="password" name="new_pass" id="new_pass">
</div>
<div class="form-group">
<label for="confirm_pass">Confirm Password :</label>
<input class="form-control" type="password" name="confirm_pass" id="confirm_pass">
</div>
<div class="modal-footer">
<!-- <input type="submit" name="submit" class="btn btn-block btn-warning" value="Save changes" /> -->
<button type="submit" name="submit" class="btn btn-success" id="submitForm" value="Save changes">Save Changes</button>
<button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
</div>
</form>
</div>
</div>
</div>
</div>
<!--/.modal -->
custom.js file:
$('#edit').on('hidden.bs.modal', function() {
location.reload();
});
/* must apply only after HTML has loaded */
$(document).ready(function() {
$("#updateForm").on("submit", function(e) {
$(".error").hide();
var hasError = false;
var currentpass = $("#current_pass").val();
var newpass = $("#new_pass").val();
var cnfpass = $("#confirm_pass").val();
if (currentpass == '') {
$("#current_pass").after('<span class="error text-danger"><em>Please enter your current password.</em></span>');
//$('#currentPass-group').addClass('has-error'); // add the error class to show red input
//$('#current_pass').append('<div class="help-block">Please enter your current password.</div>'); // add the actual error message under our input
hasError = true;
} else if (newpass == '') {
$("#new_pass").after('<span class="error text-danger"><em>Please enter a password.</em></span>');
hasError = true;
} else if (cnfpass == '') {
$("#confirm_pass").after('<span class="error text-danger"><em>Please re-enter your password.</em></span>');
hasError = true;
} else if (newpass != cnfpass) {
$("#confirm_pass").after('<span class="error text-danger"><em>Passwords do not match.</em></span>');
hasError = true;
}
if (hasError == true) {
return false;
}
if (hasError == false) {
var postData = $(this).serializeArray();
var formURL = $(this).attr("action");
$.ajax({
url: formURL,
type: "POST",
data: postData,
success: function(data, textStatus, jqXHR) {
$('#edit .modal-header .modal-title').html("Result");
$('#edit .modal-body').html(data);
$("#submitForm").remove();
//document.location.reload();
},
error: function(jqXHR, status, error) {
console.log(status + ": " + error);
}
});
e.preventDefault();
}
});
$("#submitForm").on('click', function() {
$("#updateForm").submit();
});
});
update-info.php
To use this code for multiple form add ajax code in one function and call that function whenever you want to.
To prevent page from reloading when someone click on cancel
Instead of using
$('#edit').on('hidden.bs.modal', function () {
location.reload();
});
Add one click event on cross and then reload page by location.reload();
You can use e.preventDefault(); and instead of submit use click event
$("#submitForm").on("click", function(e) {
e.preventDefault();

Angular validations: Restrict server request if user enters invalid email or password

<form name="LPform" novalidate>
<div class="form-row clearfix">
<label class="lbl-fld" style="margin-left: 12%;width:20%;">Email ID</label>
<input class="mob-adj-inpbx " type="email" name="uemail" ng-model="useremail" placeholder=" me#example.com" ng-required="true"/>
<div class="valid-chk validation-loginpopup" ng-show="LPform.uemail.$dirty && allow_Invalid">
<i style="font-size: 1.15em;padding:0px;" ng-class="{'false':'icon-close', 'true': 'icon-correct'}[LPform.uemail.$valid]" class="icon-correct"></i>
</div>
<div class="error-prompt" ng-show="LPform.uemail.$dirty && allow_Invalid">
</div>
</div>
<div class="form-row clearfix">
<label class="lbl-fld" style="margin-left: 12%;width:20%;">PASSWORD</label>
<input class="mob-adj-inpbx" type="password" name="upassword" ng-model="userpassword" placeholder=" password" ng-required="true"/>
<div class="valid-chk validation-loginpopup" ng-show="LPform.upassword.$dirty && allow_Invalid">
<i style="font-size: 1.15em;padding:0px;" ng-class="{'false':'icon-close', 'true': 'icon-correct'}[LPform.upassword.$valid]" class="icon-correct"></i>
</div>
<div class="error-prompt" ng-show="LPform.upassword.$dirty && allow_Invalid">
</div>
</div>
<div id="server_message" class="form-row clearfix basic-error-msg-loginpopup" ng-show="server_message">
{{server_message}}
</div>
<div class="btn-container clearfix mobile-adj" style="margin-left:17.2%;">
<div class="btn-wrap btn-loginpopup">
<input style="max-height:40px;width:121%;" type="submit" name="commit" value="LOGIN" ng-click="login_request()"/>
</div>
</div>
</form>
This part is displayed to the user and the inputs are validated using angular validations. All validations are working fine.
$scope.login_request = function(){
if(LPform.useremail.$valid && LPform.userpassword.$valid) {
$scope.allow_Invalid = "true";
$http({
method: 'POST',
url: '/users/home_login',
data: {email: $scope.useremail, password: $scope.userpassword}
}).success(function (response) {
console.log(response);
window.location = response.location;
}).error(function (response) {
console.log(response);
$scope.server_message = response.server_message;
});
}
else if(!LPform.useremail.$valid) {
$scope.allow_Invalid = "true";
$scope.server_message = "Please enter valid email.";
}
else if(!LPform.userpassword.$valid) {
$scope.allow_Invalid = "true";
$scope.server_message = "Please enter valid password.";
}
else{
$scope.allow_Invalid = "true";
$scope.server_message = "Request Failed.";
}
};
This part is in javascript file where I want to use the validations to decide whether to send a request to the server or not. The conditions I have used in the if else clause is not working, which I randomly tried btw. I am aware that I can disable Login button, however, I don't want to implement this that way.
I believe your problem is that the form name is bound to $scope and isn't a global variable.
In controller change
LPform
To
$scope.LPform

Login Ajax form not working, redirecting to another page

I have created a Ajax form to handle the errors in my login form, but instead of showing errors in the form area, it directs me to another page with the json error response
<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>
My ajax code
$("#loginform").on('submit', function(event) {
event.preventDefault();
alert("Was preventDefault() called: " + event.isDefaultPrevented());
console.log("form submitted!");
var url = "/users/login-ajax/";
$.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);
}
})
});
My code for the action in views.py
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)

Categories