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');
Related
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();
}
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.
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.
I'm trying to add validation to my ResetPassword function. validation its work fine, but I got another problem my ResetPassword function not going to work after I add validation.Can anyone direct me in the right direction? thx.
HTML code:
<div class="PopUpBG">
<div class="PopUp">
<h3 class="modal-title">
<span>Reset PAssword</span>
</h3>
<form id="form">
<input type="email" name="ResetEmail" id="ResetEmail" placeholder="Email Adresse" required/>
<input type="submit" class="btn btn-success" value="Send" onclick="ResetPassword(this)"/>
</form>
</div>
</div>
ResetPassword & validation code:
function ResetPassword(e) {
var email = $("#ResetEmail").val();
if ($("#form").validate()) {
return true;
} else {
return false;
}
$(".PopUp").html("We have sent mail to you");
$.ajax(
{
type: "POST",
url: "/Account/loginRequestResetPassword",
dataType: "json",
data: {
Email: email,
},
complete: function () {
console.log("send");
$(".PopUpBG").fadeOut();
}
})
}
The issue is because you're always exiting the function before you send the AJAX request due to your use of the return statement in both conditions of your if statement.
Change your logic to only exit the function if the validation fails:
function ResetPassword(e) {
if (!$("#form").validate())
return false;
$.ajax({
type: "POST",
url: "/Account/loginRequestResetPassword",
dataType: "json",
data: {
Email: $("#ResetEmail").val().trim(),
},
success: function() {
console.log("send");
$(".PopUp").html("We have sent mail to you");
setTimeout(function() {
$(".PopUpBG").fadeOut();
}, 10000); // fadeout the message after a few seconds
},
error: function() {
console.log('something went wrong - debug it!');
}
})
}
Also note that I amended the logic to only show the successful email message after the request completes. Your current code can show the 'email sent' message to the user, even though there is still scope for the function to fail.
I'm new to Jquery ajax, and I'm trying to submit certain field only for checking instead of submitting the whole form. Here I have made a function for checking the username whether is it available, and it works fine, but I doesn't want it to submit the whole form when doing the checking.
Here is my script:
<form id="userCheck">
<input type="text" class="register_field" name="fr_username" id="fr_username" />
<input type="text" class="register_field" name="fr_password" id="fr_password" />
<input type="text" class="register_field" name="fr_password1" id="fr_password1" />
</form>
<script>
$.validator.addMethod("duplicateCheck", function(value, element) {
$.ajax({
type: 'POST',
url: '../a/checkDuplicate',
data: $("#userCheck").serialize(),
dataType: 'json'
}).success(function(data){
if(data.status == '1'){
console.log('Available!');
}
else {
console.log('not available');
$('#fr_dupChkU_msg').html('');
}
});
});
</script>
In short, that is how you get a value of an input field with jQuery:
<script type="text/javascript">
var username = $('#fr_username').val();
$.validator.addMethod('duplicateCheck', function(value, element) {
$.ajax({
type: 'POST',
url: '../a/checkDuplicate',
data: {username: username},
}).success(function(data){
if(data.status == '1'){
console.log('Available!');
}
else {
console.log('not available');
$('#fr_dupChkU_msg').html('');
}
});
});
</script>