Submit login with Jquery - javascript

When I press the Login button I get a 500 Internal server error in the console. What's the right way to get POST using jQuery? Can you help me?
<button class="login100-form-btn" type="submit" name="login" value="login" id="Login">
Login
</button>
$(function() {
$("#Login").click(function() {
var username_val = $("#username").val();
var password_val = $("#password").val();
var info_creds = 'username=' + username_val + '&password=' + password_val;
if (username_val == '' || password_val == '') {
$("#alert_response_ko").show();
$("#alert_response_ko").html("<p>Devi inserire username e password!</p>");
$("#alert_response_ko").fadeOut(8000);
} else {
$.ajax({
type: "POST",
url: "login.php",
data: info_creds,
cache: false,
success: function(response) {
if (response == 'wrong!') {
console.log('ko');
$("#alert_response_ko").show();
$("#alert_response_ko").html("<p>Username e/o Password Errati!</p>");
$("#alert_response_ko").fadeOut(8000);
}
if (response == 'login_ok!') {
console.log('ok');
window.setTimeout(function() {
window.location.href = './homepage.php';
}, 10);
}
}
});
}
return false;
})
});

The 500 Internal Server Error is a "server-side" error, meaning the problem is not with your PC or Internet connection but instead is a problem with the web site's server.
If you want to use Post, you have to send data as Object Change your
Ajax Function to...
$.ajax({
type: 'POST',
url: 'login.php',
data: {
username: username_val,
password: password_val,
},
cache: false,
success: function (response) {
if (response == 'wrong!') {
console.log('ko');
$('#alert_response_ko').show();
$('#alert_response_ko').html(
'<p>Username e/o Password Errati!</p>'
);
$('#alert_response_ko').fadeOut(8000);
}
if (response == 'login_ok!') {
console.log('ok');
window.setTimeout(function () {
window.location.href = './homepage.php';
}, 10);
}
},
});

Consider the following code.
$(function() {
function showAlert(msg) {
console.log(msg);
$("#alert_response_ko").html("<p>" + msg + "</p>").show().fadeOut(8000);
}
function login(page, user, pass) {
$.ajax({
url: page,
data: {
username: user,
password: pass
},
cache: false,
success: function(results) {
if (results == 'login_ok!') {
console.log('Login Successful');
window.setTimeout(function() {
window.location.href = './homepage.php';
}, 10);
} else {
showAlert("Username e/o Password Errati!");
}
},
error: function(x, e, n) {
showAlert("Username e/o Password Errati! " + e + ", " + n);
}
});
}
$("#Login").closest("form").submit(function(e) {
e.preventDefault();
var username_val = $("#username").val();
var password_val = $("#password").val();
if (username_val == '' || password_val == '') {
showAlert("Devi inserire username e password!");
} else {
login("login.php", username_val, password_val);
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form>
<input type="text" id="username" placeholder="User" /> <input type="password" id="password" placeholder="Password" /> <button class="login100-form-btn" type="submit" name="login" value="login" id="Login">
Login
</button>
</form>
<div id="alert_response_ko"></div>
This might help identify issues. As was suggested, the 500 status is a general Web Server failure. It means that the Web Server encountered an error and may be configured to suppress the error message itself.
Check your PHP Logs and Error handling settings. Better to reveal errors while testing and then hide them when in production.

Related

jQuery Ajax Email Validator

I have a simple form for a person to fill in their email address. My Ajax script is set to check this address with the database and validate if it exists or not. That step works but I'm stuck on getting the form to submit if the email doesn't exist.
This is my HTML
<form action="user_add.php" method="post" id="addform">
<input
type="text"
class="form-control"
name="email"
id="email"
required
value=""
/>
Check
</form>
This is my JS
function check() {
$.ajax({
url: 'checkusers.php',
data: {
email: $('#email').val()
},
type: 'POST',
dataType: 'json',
success: function (data) {
if (data == true) {
alert('Please note: A user with this email address already exists.')
return false
} else if (data == false) {
//return true; --- this doesn't work
//$('form').submit(); --- this doesn't work
$('form').trigger('submit') // --- this doesn't work
}
},
error: function (data) {
//error
}
})
}
What am I doing wrong here?
Using regular expressions is probably the best way.
function validateEmail(email) {
const re = /^(([^<>()[\]\\.,;:\s#"]+(\.[^<>()[\]\\.,;:\s#"]+)*)|(".+"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
return re.test(String(email).toLowerCase());
}
function check(){
var email = $('#email').val();
if (validateEmail(email)) {
$.ajax({
url: "checkusers.php",
data: {
'email' : email
},
type: "POST",
dataType: 'json',
success: function(data) {
if(data == true) {
alert('Please note: A user with this email address already exists.');
return false;
}
else if(data == false) {
//return true; --- this doesn't work
//$('form').submit(); --- this doesn't work
$('form').trigger('submit'); // --- this doesn't work
}
},
error: function(data){
//error
}
});
} else {
// error email not valid
}
}
Thank you to everyone for your input. I had a stray submit button higher up on the page I was working on
<input type="submit" id="submit" name="submit" value="Submit" class="btn btn-primary">
When I took this out, the following bit worked:
$('form').trigger('submit');

reCAPTCHA form submitting twice on second submit

I am creating a form using reCAPTCHA v2 and want the form to be able to be submitted again without reloading the page. When I submit the form for the first time, it works as expected. However, when I submit the form again without reloading the page, my CaptchaValidate function will be called twice, first returning false, then returning true. Why is this happening? Any help would be brilliant, thanks.
HTML
<form id="form" method="POST">
<label for="name">Name</label>
<input class="form-control" id="name" name="name">
<label for="age">Age</label>
<input class="form-control" id="age" name="age">
<button class="g-recaptcha" data-sitekey="myKey" data-callback="onSubmit" type="submit">Submit</button>
</form>
Javascript
function onSubmit(response) {
$('#form').submit(function (e) {
e.preventDefault();
const formData = $(this).serializeArray();
$.ajax({
url: '/Home/CaptchaValidate',
type: 'POST',
dataType: 'text',
data: { dataToken: response },
success: function (resultData) {
if (resultData == 'true') {
//do something
}
else {
$('.error-message').html('could not submit form');
}
},
error: function (err) {
console.log(err);
}
})
}).submit();
grecaptcha.reset();
}
Controller
[HttpPost]
public async Task<string> GetCaptchaData(string dataToken)
{
HttpClient httpClient = new HttpClient();
string secretKey = "mySecretKey";
var res = httpClient.GetAsync("https://www.google.com/recaptcha/api/siteverify?secret=" + secretKey + "&response=" + dataToken).Result;
if (res.StatusCode != HttpStatusCode.OK)
return "false";
string JSONres = res.Content.ReadAsStringAsync().Result;
dynamic JSONdata = JObject.Parse(JSONres);
if (JSONdata.success != "true")
return "false";
return "true";
}
try use e.stopImmediatePropagation();
it stops the rest of the event handlers from being executed.
function onSubmit(response) {
$('#form').submit(function (e) {
e.preventDefault();
e.stopImmediatePropagation(); // new line
const formData = $(this).serializeArray();
$.ajax({
url: '/Home/CaptchaValidate',
type: 'POST',
dataType: 'text',
data: { dataToken: response },
success: function (resultData) {
if (resultData == 'true') {
//do something
}
else {
$('.error-message').html('could not submit form');
}
},
error: function (err) {
console.log(err);
}
})
}).submit();
grecaptcha.reset();
}

Remove the required attribute after the sucees of form submission

I have a form on click of submit the input box is highlighted with the red color border if it is empty. Now i have jquery ajax form submission on success of the form i will display a message "data submitted" and i will reset the form so all the input fields will be highlighted in red color. Now i want to empty the fields after the success of form submission and it should not be highlighted in red color.
HTML
(function() {
'use strict';
window.addEventListener('load', function() {
var form = document.getElementById('index-validation');
form.addEventListener('submit', function(event) {
if (form.checkValidity() === false) {
event.preventDefault();
event.stopPropagation();
}
form.classList.add('was-validated');
}, false);
}, false);
})();
$(".index-form").submit(function(e) {
e.preventDefault();
return false;
}
else {
var ins_date = new Date($.now()).toLocaleString();
var parms = {
name: $("#name").val(),
email: $("#email").val(),
inserted_date: ins_date
};
var url2 = "http://localhost:3000/api";
$.ajax({
method: 'POST',
url: url2 + "/homes",
async: false,
dataType: "json",
contentType: "application/json; charset=utf-8",
data: JSON.stringify(parms),
success: function(data) {
console.log('Submission was successful.');
$(".alert-success").removeClass("d-none");
$(".alert-success").fadeTo(2000, 500).slideUp(500, function() {
$(".alert-success").slideUp(500);
});
$('.index-form')[0].reset();
console.log(data);
},
error: function(data) {
console.log('An error occurred.');
console.log(data);
},
})
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form class="container index-form" id="index-validation" novalidate>
<input class="form-control" type="text" id="name" name="name" placeholder="Your name" required>
<input class="form-control" type="email" id="email" name="email" placeholder="Email Address" required>
<div class="invalid-feedback">Please Enter a Valid Email Id.</div>
<input type="submit" id="submit" class="btn btn-default btn-lg btn-block text-center" value="Send">
</form>
I'm not clear with your question, Do you want to reset form or remove the error class. But anyways I'll try solving out both :
SCRIPT
<script type="text/javascript">
(function() {
'use strict';
window.addEventListener('load', function() {
var form = document.getElementById('index-validation');
form.addEventListener('submit', function(event) {
if (form.checkValidity() === false) {
event.preventDefault();
event.stopPropagation();
}
form.classList.add('was-validated');
}, false);
}, false);
})();
$(".index-form").submit(function(e) {
e.preventDefault();
return false;
} else {
var ins_date=new Date($.now()).toLocaleString();
var parms = {
name : $("#name").val(),
email : $("#email").val(),
inserted_date:ins_date
};
var url2="http://localhost:3000/api";
$.ajax({
method: 'POST',
url: url2 + "/homes",
async: false,
dataType : "json",
contentType: "application/json; charset=utf-8",
data: JSON.stringify(parms),
success: function(data){
console.log('Submission was successful.');
//if you are removing specific property from class
$(".alert-success").css('display', 'none');
$(".alert-success").fadeTo(2000, 500).slideUp(500, function(){
$(".alert-success").slideUp(500);
});
$("form")[0].reset();
console.log(data);
}, error: function (data) {
console.log('An error occurred.');
console.log(data);
},
})
}
});
</script>
Jquery doesn't support any method such as reset() of javascript, So you can trigger javascript's reset() method.
Feel free to ask doubts if stuck. Happy coding....!!!!!
$(this.('.index-form').find("input[type=text]").val("");
You can just empty the form value by giving the .val() as empty, you have to give this on after your ajax response.
and also instead of using fade in and fade out just try to use hide and show function both may work like same.

How to return invalid password error message via Ajax - MVC

I have login page where, user enter their Email and password , but i want display a alert or text like (you entered invalid password), when they enter wrong password. i already check Checkpass is not null do something and in else i dont know what should i do to be honest.Can anyone please help me or point me in the right direction!
Thanks in advance:)
Controller:
[HttpPost]
public JsonResult Login(string Mail, string pass)
{
var hashedPass = PasswordSecurity.PasswordStorage.CreateHash(pass);
using (DbNameSpace db = new DbNameSpace())
{
var query = from cbr in db.Contact_Business_Relation
join c in db.Contact on cbr.Contact_No_ equals c.Company_No_
join sa in db.Sales_Header on cbr.No_ equals sa.Sell_to_Customer_No_
join px in db.PX2 on c.E_Mail equals px.Email_ID
where c.E_Mail == Mail.ToLower()
select new
{
Mail = c.E_Mail,
pass = px.PS,
};
var user = query.FirstOrDefault();
var CheckPass = PasswordSecurity.PasswordStorage.VerifyPassword(pass, user.pass);
if (user != null && CheckPass) //Checkpassword
{
Session["Email"] = user.Mail.ToString();
}
else {
// ??
}
return Json(user, JsonRequestBehavior.AllowGet);
}
}
JavaScript:
<script>
$(document).ready(function () {
$("#login").click(function (e) {
var email = $("input[name=Mail]").val();
var password = $("input[name=pass]").val();
e.preventDefault();
$.ajax({
type: "POST",
dataType: "json",
url: '#Url.Action("Login", "Account")',
data: { Mail: email, pass: password },
success: function (status) {
if (status) {
window.location.href = "/Account/Index";
}
}
});
});
});
</script>
View:
<form autocomplete="on" class="login100-form validate-form">
<div>
<label>E-mail</label>
<div class="wrap-input100 validate-input" data-validate="Valid email is required: ex#abc.xyz">
<input class="input100" type="email" id="Email" name="Mail" placeholder="E-mail">
</div>
<label>Password</label>
<div class="wrap-input100 validate-input" data-validate="Password is required">
<input class="input100" type="password" id="Password" name="pass" placeholder="Kodeord">
</div>
<div id="invalidpassword"></div>
<div class="container-login100-form-btn">
<button id="login" class="login100-form-btn">
Log in
</button>
</div>
</form>
Check out this jquery tutorial. I personally would use the Fail and Done callback methods. Modify your c# controller to return different HTTP status codes. Use HTTP 200 when they pass a good username and password. Use HTTP 400 when they pass a bad password this should trigger the Fail() callback and allow you to alert on the failure.
https://learn.jquery.com/ajax/jquery-ajax-methods/
// Using the core $.ajax() method
$.ajax({
// The URL for the request
url: "post.php",
// The data to send (will be converted to a query string)
data: {
id: 123
},
// Whether this is a POST or GET request
type: "GET",
// The type of data we expect back
dataType : "json",
})
// Code to run if the request succeeds (is done);
// The response is passed to the function
.done(function( json ) {
$( "<h1>" ).text( json.title ).appendTo( "body" );
$( "<div class=\"content\">").html( json.html ).appendTo( "body" );
})
// Code to run if the request fails; the raw request and
// status codes are passed to the function
.fail(function( xhr, status, errorThrown )** {
alert( "Sorry, there was a problem!" );
console.log( "Error: " + errorThrown );
console.log( "Status: " + status );
console.dir( xhr );
})
// Code to run regardless of success or failure;
.always(function( xhr, status ) {
alert( "The request is complete!" );
});
The normal thing to do would be to set the response status to 401 and omit the usual data payload that would be sent with a successful response. Then it's up to the client code to recognize the error status and respond appropriately (e.g. perhaps by showing an alert and remaining on the name/password form); this client-side behavior would be specified in the $.ajax call.
It's an example. Hope to help, my friend.
[HttpPost]
public JsonResult Login(string Mail, string pass)
{
var status = true;
var hashedPass = PasswordSecurity.PasswordStorage.CreateHash(pass);
using (DbNameSpace db = new DbNameSpace())
{
var query = from cbr in db.Contact_Business_Relation
join c in db.Contact on cbr.Contact_No_ equals c.Company_No_
join sa in db.Sales_Header on cbr.No_ equals sa.Sell_to_Customer_No_
join px in db.PX2 on c.E_Mail equals px.Email_ID
where c.E_Mail == Mail.ToLower()
select new
{
Mail = c.E_Mail,
pass = px.PS,
};
var user = query.FirstOrDefault();
var CheckPass = PasswordSecurity.PasswordStorage.VerifyPassword(pass, user.pass);
if (user != null && CheckPass) //Checkpassword
{
Session["Email"] = user.Mail.ToString();
}
else {
status = false;
}
return Json(status, JsonRequestBehavior.AllowGet);
}
}
In Javascript:
<script>
$(document).ready(function () {
$("#login").click(function (e) {
var email = $("input[name=Mail]").val();
var password = $("input[name=pass]").val();
e.preventDefault();
$.ajax({
type: "POST",
dataType: "json",
url: '#Url.Action("Login", "Account")',
data: { Mail: email, pass: password },
success: function (status) {
if (status) {
window.location.href = "/Account/Index";
}else{
$('#invalidpassword').html('You have entered wrong password!');
}
}
});
});
});
</script>
This is how i end up to archive how to return invalid password error message , maybe it help someone on day :)
I created a enum to hold the values for MessageType:
public enum MessageType
{
Valid,
InvalidEmail,
InvalidUerNameAndPass,
}
and then i change my Controller to get different MessageType:
public JsonResult Login(string Mail, string pass)
{
MessageType messageType = MessageType.InvalidEmail;
using (DbNamesapce db = new DbNamesapce())
{
var query = // do Join
select new
{
//Select Something
};
var user = query.FirstOrDefault();
if (user == null)
{
return Json(new { messageType = MessageType.InvalidEmail }, JsonRequestBehavior.AllowGet);
}
if (user != null && CheckPass)
{
messageType = MessageType.Valid;
}
else
{
messageType = MessageType.InvalidUerNameAndPass;
}
return Json(new { messageType = messageType }, JsonRequestBehavior.AllowGet);
}
}
and i change my script to :
<script>
$(document).ready(function () {
$("#login").click(function (e) {
var email = $("input[name=Mail]").val();
var password = $("input[name=pass]").val();
e.preventDefault();
$.ajax({
type: "POST",
dataType: "json",
url: '#Url.Action("Login", "Account")',
data: { Mail: email, pass: password },
success: function (response) {
switch ($.trim(response.messageType))
{
case '#Convert.ToInt32(YourNAmeSpace.Models.MessageType.Valid)':
alert("Valid");
break;
case '#Convert.ToInt32(YourNAmeSpace.Models.MessageType.InvalidEmail)':
alert("InvalidUerNameAndPass");
break;
case '#Convert.ToInt32(YourNAmeSpace.Models.MessageType.InvalidUerNameAndPass)':
alert("InvalidUerNameAndPass");
break;
}
}
});
});
});
</script>

event.preventDefault(); only works some of the time with submit form

I am using the Mailchimp API to submit a form. The goal is to prevent the default callback provided by Mailchimp. The majority of the time event.preventDefault() is behaving as it should. Then randomly it will not work:
$(function () {
var $form = $('#mc-embedded-subscribe-form');
$('#mc-embedded-subscribe').on('click', function(event) {
if(event) event.preventDefault();
register($form);
});
});
function register($form) {
$.ajax({
type: $form.attr('method'),
url: $form.attr('action'),
data: $form.serialize(),
cache : false,
dataType : 'json',
contentType: "application/json; charset=utf-8",
error : function(err) { alert("Could not connect to the registration server. Please try again later."); },
success : function(data) {
if (data.result != "success") {
// Something went wrong, do something to notify the user. maybe alert(data.msg);
var message = data.msg
var messageSh = data.msg.substring(4);
if (data.msg == '0 - Please enter a value' || data.msg == '0 - An email address must contain a single #') {
$('#notification_container').html('<span class="alert">'+messageSh+'</span>');
} else {
$('#notification_container').html('<span class="alert">'+message+'</span>');
}
} else {
// It worked, carry on...
var message = data.msg;
$('.popup-promo-container').addClass('thanks');
$('.checkboxes, #mc_embed_signup_scroll').addClass('hidden');
$('.complete-promo').html(message).removeClass('hidden');
setTimeout(function() {
document.querySelector('.popup-promo').style.display = "none";
},20000);
}
}
});
}
Try
take off ready function.
remove if on event
Code:
var $form = $('#mc-embedded-subscribe-form');
$('#mc-embedded-subscribe').on('click', function(event) {
event.preventDefault();
register($form);
});

Categories

Resources