Ajax submit certain field - javascript

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>

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();
}

im using jquery/ajax for login. Sending works and server side returns to log in, but this fails

I have created a login system with PHP, however, i also added two factor authentication. I wanted to log in without having to refresh the page so it looks better when asking for the 2FA code
The way i have done this is by sending the username and password via ajax. my php script then checks this and then it would echo login or error
Here's my javascript code
$(document).ready(function() {
$('#login-form').submit(function(e) {
e.preventDefault();
$.ajax({
type: "POST",
url: 'inc/auth.php',
data: $(this).serialize(),
dataType: 'text',
success: function(data)
{
alert(data);
if (data === 'login') {
window.location = '/user-page.php';
}
else {
alert('Invalid Credentials');
}
},
});
});
});
This works fine, when i alert the data i get 'login' (without quotes, obviously) however it doesn't send me to user-page.php, instead, it gives me the invalid credentials alert. Despite the php page returning login, javascript is like "nope!"
What am i doing wrong?
Here's my form
<form class="form" id="login-form" name="login-form" method="post" role="form" accept-charset="UTF-8">
<div class="form-group">
<label class="sr-only" for="exampleInputEmail2">Gebruikersnaam</label>
<input type="username" class="form-control" id="gebruikersnaam" name="gebruikersnaam" placeholder="gebruikersnaam" required>
</div>
<div class="form-group">
<label class="sr-only" for="exampleInputPassword2">Wachtwoord</label>
<input type="password" class="form-control" id="wachtwoord" name="wachtwoord" placeholder="Password" required>
<div class="help-block text-right">Forget the password ?</div>
</div>
<div class="form-group">
<button type="submit" class="btn btn-primary btn-block">Sign in</button>
</div>
</form>
I run the javascript from this page via <script src="auth.js"></script>. I also tried putting it directly inside script tags witch failed too.
This is for testing purpose
I believe your dataType should be either html or json
$(document).ready(function() {
$('#login-form').submit(function(e) {
e.preventDefault();
$.ajax({
type: "POST",
url: 'inc/auth.php',
data: $(this).serialize(),
dataType: 'html',
success: function(data)
{
alert(data);
if (data == 'login') {
window.location = '/user-page.php';
}
if (data == 'failed') {
alert('Invalid Credentials');
}
},
});
});
});
In absence of your server logic
Your php inc/auth.php FOR Testing purpose
//$gebruikersnaam= $_POST['gebruikersnaam'];
//$wachtwoord= $_POST['wachtwoord'];
$gebruikersnaam= 'nancy';
$wachtwoord= 'nancy123';
if($gebruikersnaam=='nancy' && $wachtwoord=='nancy123')
{
echo "login";
}
else
{
echo "failed";
}
As for CSRF attack mentioned by SO Scholar in the comment. you will need to generate something like md5 token that will be stored in a session. you will now send it with each request eg. in a hidden form input and verify that it matches the one on the server side. if match allow login otherwise trigger impersonation
Updates
$(document).ready(function() {
$('#login-form').submit(function(e) {
e.preventDefault();
$.ajax({
type: "POST",
url: 'inc/auth.php',
data: $(this).serialize(),
dataType: 'JSON',
success: function(data)
{
alert(data);
if (data.login == 'success') {
window.location = '/user-page.php';
}
if (data.login == 'failed') {
alert('Invalid Credentials');
}
},
});
});
});
PHP
<?php
error_reporting(0);
$gebruikersnaam= 'nancy';
$wachtwoord= 'nancy123';
if($gebruikersnaam=='nancy' && $wachtwoord=='nancy123')
{
$return_arr = array('login'=>'success');
}
else
{
$return_arr = array('login'=>'failed');
}
echo json_encode($return_arr);

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.

Adding email into MySQL database with PHP, JQuery, Ajax

My code so far
main.js file:
$('#addButton').on('click', function() {
var email = $('#userInput').val();
$.ajax({
type: "post",
url: 'validation.php',
success: function(html) {
alert(html);
}
});
});
index.html file:
<form method="post">
<input type="text" name="email" placeholder="Your Email" id="userInput"><br>
<button type="submit" name="submit" id="addButton">Add User</button>
</form>
<!-- jQuery first, then Bootstrap JS. -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.2/js/bootstrap.min.js" integrity="sha384-vZ2WRJMwsjRMW/8U7i6PWi6AlO1L79snBrmgiDpgIWJ82z8eA5lenwvxbMV1PAh7" crossorigin="anonymous"></script>
<script src="main.js"></script>
validation.php file:
<?php
if (array_key_exists("submit", $_POST)) {
$link = mysqli_connect("localhost", "my_username", "my_password", "my_db");
if (mysqli_connect_error()) {
die("Error Connecting To Database");
}
if (validateEmail($_POST['email'])) {
$query = "INSERT INTO `users` (`email`) VALUES ('".mysqli_real_escape_string($link, $_POST['email'])."')";
if (mysqli_query($link, $query)) {
$success = "Email: ".$_POST['email']." added";
} else {
echo "Error in query";
}
}
}
?>
Here is my validate email function:
function validateEmail($email) {
if (!preg_match('/^([a-z0-9\+\_\-\.]+)#([a-z0-9\+\_\-\.]{2,})(\.[a-z]{2,4})$/i', $email)) {
echo "Invalid Email";
return false;
} else {
$domain = array('umich.edu');
list(, $user_domain) = explode('#', $email, 2);
return in_array($user_domain, $domain);
}
}
Am I performing my Ajax request incorrectly because it never adds the email to the database?
Try something this :
$.ajax({
type: 'POST',
// make sure you respect the same origin policy with this url:
url: 'validation.php',
data: {
'email': email
},
success: function(html){
}
});
There is a lot of way to do that, but I think this is the best way and the easiest way for you to make it work base on your current code.
First thing, You don't need to use type="submit" button when using AJAX.
HTML should be,
<form id='emailform'>
<input type="text" name="email" placeholder="Your Email" id="userInput"><br>
<button type="button" name="submit" id="addButton">Add User</button>
</form>
Your JS should be something like this, use jQuery's .serialize() function to your form:
$('#addButton').on('click', function() {
var email = $('#userInput').val();
$.ajax({
type: "post",
url: 'validation.php',
data: $('#emailform').serialize(),
dataType: "html",
success: function(html) {
alert(html);
}
});
});
Try this ;)
$('#addButton').on('click', function(event){
/* prevent default behavior of form submission. */
event.preventDefault();
var email = $('#userInput').val();
$.ajax({
type: "post",
data: {
email: email,
submit: 1
},
url: "validation.php",
success: function(html){
alert(html);
}
});
});
You need to send email and submit because you wrapped all code in if (array_key_exists("submit", $_POST)) { means you are checking if the submit field submitted or not.
You can use below function also in your main.js.
Please remember that whenever you run any post request and if you want to send some data to server you need to mention that variable or json one of the parameter.
$(document).ready(function(){
$("button").click(function(){
$.post("demo_test_post.asp", {email: "hello#hello.com"},
function(data, status){
alert("Data sent!");
});
});
});
Or you can use the below code also for better understanding
$.ajax({
type: 'POST',
// make sure you respect the same origin policy with this url:
url: 'validation.php',
data: {
email: email
},
contentType:'application/json',
success: function(html){
}
});

Categories

Resources