jQuery AJAX not working when passing data to a PHP page - javascript

Validation part of my jQuery works, however, the AJAX part does not seem to be doing anything and I am wondering why?
It comes up with no errors and the registration works perfect without the AJAX, however, I have to use it.
HTML form in register.php:
<form method="post" action="register.php" name="registration-form" id="register-form">
<div class="form-group" id="email-group">
<label for="email"> Email address </label>
<input id="email" type="email" name="email" class="form-control" aria-describedby="emailHelp" required>
</div>
<div class="form-group" id="password-group">
<label for="password"> Password </label>
<input id="password" type="password" name="password" class="form-control" required>
</div>
<div class="form-group form-check">
<input type="checkbox" name="terms" class="form-check-input" required> I accept the <a class="privacy-link"
href="privacy-policy.php"> Privacy Policy </a>
</div>
<button type="submit" name="register_user" class="btn btn-primary" value="register_user">Register</button>
</form>
jQuery with AJAX:
$(document).ready(function () {
$("#register-form").submit(function (event) {
event.preventDefault();
}).validate({
rules: {
email: {
minlength: 6
},
password: {
minlength: 8
}
},
messages: {
email: "Email should be at least 6 characters",
password: "Password should be at least 8 characters"
},
submitHandler: function (form) {
var email = $("#email").val();
var password = $("#password").val();
$.ajax({
url: "register.php",
contentType: "application/json",
type: "POST",
data: {
email: email,
password: password
}
}).done(function (response) {
// some actions
});
}
});
});
register.php PHP to handle it:
if (isset($_POST['register_user'])) {
/* Others */
}
I tried various "isset", but to no avail.

there are few things wrong i see here.
maybe you should not catch the "submit" event of your form, i believe validation plugin take care of it.
as per the doc : https://jqueryvalidation.org/validate/#submithandler
maybe you should remove this part :
.submit(function(event) {
event.preventDefault();
})
in your ajax call, you submit 2 post variables email and password
but in your PHP file you try to retrieve $_POST['user_registration'] variable which DOES NOT EXIST because you didn't submit your form to the server's register.php file, you submitted only the 2 variables email and password
I suggest you using FormData (https://developer.mozilla.org/en-US/docs/Web/API/FormData/FormData) so you only have to update the following piece of code to make it work (in theory)
example
data = new FormData(document.getElementById('#register-form'));
$.ajax({
url: "register.php",
type: "POST",
data: data,
processData: false,
contentType: false,
})
you can refer to this SO question https://stackoverflow.com/a/8244082/5856233

Related

Email input value come undefined on alert using javascript

I have form which contain email input field
<form id="TypeValidation" action="" method="post" enctype='multipart/form-data'>
<div class="form-group has-label col-sm-6">
<label>
Email
</label>
<input class="form-control" name=email" type="email" required>
</div>
<div class="card-footer text-center">
<button type="submit" name="add_usr_acc" id="add_usr_acc" value="add_usr_acc" class="btn btn-primary" >Add</button>
</div>
</div>
</form>
Issue is that in script code when alert on email then come undefined. how to get value in which user type a email
<script>
$("#TypeValidation").on('submit', (function(e) {
var email = $(this).find('input[name="email"]').val();
alert(email); {
e.preventDefault();
$.ajax({
url: "fn_acc_submit.php?addUsraccID=" + addUsraccID,
type: "POST",
data: new FormData(this),
contentType: false,
cache: false,
processData: false,
dataType: "html",
beforeSend: function() {
$("#add_usr_acc").prop('disabled', 'disabled')
},
success: function(result) {
alert(result);
location.reload();
if (result == '1') {
location.replace("lst_user_account.php");
} else {
location.replace("add_user_account.php");
}
}
});
}
}));
</script>
Please fix my problem where I am doing wrong.
Problem is in your HTML code at below line:
<input class="form-control" name=email" type="email" required>
Here name=email" is not valid.
Change this to name="email"
In you input field, it should name="email". You forgot to add opening quotes.

Jquery form submitting before validation

I want to validate a form for inputs with the 'required' attributes but it appears that "e.preventDefault()" is not working. The form submits and the POST succeeds but with the unvalidated data and I can't find where the problem is.
<form>
<label for="name" class="control-label">Name</label>
<input type="text" id="name" class="form-control" required>
<label for="phone" class="control-label">Phone Number</label>
<input type="text" id="phone" class="form-control" required>
<label for="email" class="control-label">Email address</label>
<input type="email" id="email" class="form-control" required>
<div id="form-response"></div>
<button class="btn btn-lg btn-primary btn-block" id="submit" type="submit" style="background-color:#28547C;">Request Appointment</button>
</form>
JS:
$(document).ready(function() {
$("#submit").click(function(e) {
e.preventDefault();
var name = $("#name").val(),
email = $("#email").val(),
phone = $("#phone").val()
$.ajax({
type: "POST",
url: 'https://a2xvt72c0c.execute-api.us-west-2.amazonaws.com/prod',
contentType: 'application/json',
data: JSON.stringify({
'name': name,
'phone':phone,
'email': email
}),
success: function(res) {
$('#form-response').html('<div class="alert alert-info" role="alert">Thank you! Appointment request has been sent. We will contact you soon. </div>');
},
error: function() {
$('#form-response').html('<div class="alert alert-info" role="alert">Something went wrong... We are working on it!</div>');
}
});
})
});
JS Fiddle: https://jsfiddle.net/yhgz55y0/
Right now you are using a click event and not a submit event. If you switch it to:
$("#submit").submit(function(e) {...
the validation works.
Your form is submitting because you are calling the $.post() immediately without stopping. You want to run validation against your name, email and phone variables and if any are not valid, return early or put the entire thing into an if block.
What e.preventDefault() does is prevents the browser built-in actions. But as your form has no action or target properties, you are effectively canceling a no-op, hence why this is not behaving as you expect it to.
preventDefault is a function that prevents a normal task from executing. Here you prevent the click on a button. A button doesn´t have a function in this form so there won´t be any difference. You want to prevent de form from submiting. If you change your code to this:
$(document).ready(function() {
$("form").submit(function(e) {
e.preventDefault();
var name = $("#name").val(),
email = $("#email").val(),
phone = $("#phone").val()
$.ajax({
type: "POST",
url: 'https://a2xvt72c0c.execute-api.us-west-2.amazonaws.com/prod',
contentType: 'application/json',
data: JSON.stringify({
'name': name,
'phone':phone,
'email': email
}),
success: function(res) {
$('#form-response').html('<div class="alert alert-info" role="alert">Thank you! Appointment request has been sent. We will contact you soon. </div>');
},
error: function() {
$('#form-response').html('<div class="alert alert-info" role="alert">Something went wrong... We are working on it!</div>');
}
});
})
});
This assuming you only have 1 form on your page. This will prevent the form from submiting.

Bootstrap validator.js not communicating with my PHP

I'm a novice coder, and i'm having trouble putting a simple form together using validator.js
Basically since trying to build in the validation the form has stopped working, my guess is the 'data: $('#send-form').serialize(),' has not got the correct path or syntax, but i could be wrong.
As soon as i add:
$.ajax({
type: "POST",
url: "process.php",
data: $('#send-form').serialize(),
}
the alerts do not fire!
<form class="contact" name="contact" id="send-form" data-toggle="validator" role="form" >
<div class="form-group">
<label class="subTitle" for="name">NAME</label><br>
<input type="text" name="name" class="form-control" placeholder="Enter your full name" data-error="Please enter your name" required>
<div class="help-block with-errors"></div><br>
</div>
<div class="form-group">
<label class="subTitle" for="email">E-MAIL</label><br>
<input type="email" name="email" pattern="[a-z0-9._%+-]+#[a-z0-9.-]+\.[a-z]{2,3}$" class="form-control" placeholder="Enter a valid email address" data-error="Invalid email address" required>
<div class="help-block with-errors"></div><br>
</div>
<div class="form-group">
<button type="submit" class="subBtn form-control">SUBMIT YOUR ENQUIRY</button>
</div>
</form>
<script>
$('#send-form').validator().on('submit', function (e) {
if (e.isDefaultPrevented()) {
alert('form is not valid');
} else {
// everything looks good!
e.preventDefault();
alert('form is valid');
// your ajax
$.ajax({
type: "POST",
url: "process.php",
data: $('#send-form').serialize(),
}
});
</script>
Should be:
$('#send-form').validator().on('submit', function (e) {
if (e.isDefaultPrevented()) {
alert('form is not valid');
} else {
// everything looks good!
e.preventDefault();
alert('form is valid');
// your ajax
$.ajax({
type: "POST",
url: "process.php",
data: $('#send-form').serialize(),
});
}
});
(untested)

Ajax Success display Message inside div displayed through jQuery

i'm trying to display a success /error message when a user login to my website through a hidden div, that is displayed by on click event jQuery. Looks like whatever i try, nothing works. Already searched over and over but can't find a solution. Any help please?
My current code:
$(document).on('submit', '#loginform',function(e){
e.preventDefault();
var formData = new FormData($(this)[0]);
$.ajax({
url: 'portal/login',
type: 'POST',
dataType:"json",
data:formData,
contentType: false,
processData: false,
success: function(data) {
if(data.status == 1) {
console.log(data.status);
$('.login_result.success').show();
} else {
$('.login_result.error').show();
}
}
});
});
$('.modaltrigger').on('click',function() {
$('#loginmodal').fadeIn(500);
});
So i'm using Ajax to validate the user login, and then at success i want to fadeIn the .login_result
EDIT
My HTML code:
<div id="loginmodal" style="display:none;">
<div id="placeHolder">
<div class="main_logo"><img src="images/logo.jpg"></div>
<form action="portal/login" method="post" class="login" name="loginform" id="loginform">
<input id="user_email" name="user_email" placeholder="Email" type="text">
<input id="user_password" name="user_password" placeholder="Senha" type="password">
<button class="search_button login_button" name="admin_login">Entrar</button>
<span><?php //echo $error; ?></span>
</form>
<div class="login_result success">Login Efetuado com sucesso, Redirecionando!</div>
<div class="login_result error">Login Inválido!</div>
</div>

Bootstrap input validation in IE

Bootstrap allows one to specify an input as required, as well as defining a data type & required pattern. Sadly, this doesn't work in any version of IE prior to IE 10.
Does anybody know of a javascript validation plugin which can just pickup and read the attributes assigned to inputs to cover the gap where IE falls short?
I ran into the same problem and i used following plugin, it is working pretty well.
Official Plugin Page
http://jqueryvalidation.org/
GitHub
https://github.com/jzaefferer/jquery-validation
CDN
http://ajax.aspnetcdn.com/ajax/jquery.validate/1.11.1/jquery.validate.min.js
EXAMPLE CODE:
It can be used easily as followed with AJAX: (if you want without AJAX simply edit that part)
<form id="example_form" action="process.php" method="POST" novalidate="novalidate">
<span style="display: none;" id="success">Success</span>
<span style="display: none;" id="failure">Failure</span>
<label for="Name">Name:<br>
<input type="text" id="txtName" required="" class="required">
</label>
<label for="Phone">Contact No:<br>
<input type="tel" id="txtPhone" required="" class="required number">
</label>
<label for="Email">Email:<br>
<input type="email" id="txtEmail" required="" class="required email">
</label>
<button type="submit">Submit</button>
</form>
$(function()
{
var form = $("#example_form").validate();
$("form#example_form").submit(function() {
if(form.valid())
{
var name = $("#txtName").val();
var email = $("#txtEmail").val();
var phone = $("#txtPhone").val();
$.ajax({
url: "process.php",
type: "POST",
data: {
'name': name,
'email': email,
'phone': phone
},
dataType: "json",
success: function(data) {
if(data.status == 'success')
{
$('#success').show();
}
else if(data.status == 'error')
{
$('#failure').show();
}
}
});
return false;
}
});
});

Categories

Resources