Ajax validation no request send to server - javascript

I apologize for opening what might be a very basic post, I am learning Ajax please keep that in mind.
I have a simple registration form.
What im trying to do
validate the form
if all is in order register new user
I have managed to get the Ajax script to register a new user but my problem comes in with the validation part hench im turning here for a bit of help and advice
HTML
<div id="regResponse">
</div>
<form class="form-horizontal" id="regForm" role="form" method="post" action="../register.php" >
<div class="form-group">
<label class="control-label col-sm-2" for="regName">Name:</label>
<div class="col-sm-10">
<input type="text" name="regName" class="form-control" id="name" placeholder="">
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2" for="regLastName">Surname:</label>
<div class="col-sm-10">
<input type="text" name="regLastname" class="form-control" id="lastname" placeholder="">
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2" for="regEmail">Email:</label>
<div class="col-sm-10">
<input type="text" name="regEmail" class="form-control" id="regEmail" placeholder="">
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2" for="regPword">Pword:</label>
<div class="col-sm-10">
<input type="text" name="regPword" class="form-control" id="regPword" placeholder="">
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2" for="confRegPword">Confirm Pword:</label>
<div class="col-sm-10">
<input type="text" name="confRegPword" class="form-control" id="regPword2" placeholder="">
</div>
JQUERY AJAX
function sendForm() {
var valid;
valid = validateContact()
if(valid){
// Get the form.
var form = $('#regForm');
// Get the messages div.
var formMessages = $('#regResponse');
// Set up an event listener for the contact form.
$(form).submit(function(e) {
// Stop the browser from submitting the form.
e.preventDefault();
// Serialize the form data.
var formData = $(form).serialize();
// Submit the form using AJAX.
$.ajax({
type: 'POST',
url: $(form).attr('action'),
data: formData
})
.done(function(response) {
// Make sure that the formMessages div has the 'success' class.
$(formMessages).removeClass('error').addClass('success');
// Set the message text.
$(formMessages).html(response); // < html();
// Clear the form.
$('').val('')
})
.fail(function(data) {
// Make sure that the formMessages div has the 'error' class.
$(formMessages).removeClass('success').addClass('error');
// Set the message text.
var messageHtml = data.responseText !== '' ? data.responseText : 'Oops! An error occured and your message could not be sent.';
$(formMessages).html(messageHtml); // < html()
});
});
}
}
function validateContact(){
var valid = true;
var name = document.getElementById("name").value;
var lastname = document.getElementById("lastname").value;
var email = document.getElementById("regEmail").value;
if(name ==''){
document.getElementById("name").style.borderColor="red";
name.value="Please Enter Name";
valid = false;
}
if(lastname ==''){
valid = false;
}
if(email ==''){
valid = false;
}
return valid;
}
PHP
if ($_SERVER["REQUEST_METHOD"] == "POST") {
//get variables from reg form
$name = $_POST['regName'];
$lastName = $_POST['regLastname'];
$email = $_POST['regEmail'];
:
$sql ="INSERT INTO members......."
($result = mysql_query($sql) or trigger_error(mysql_error()."in".$sql);
if($result){
echo '<h3 style="blue">Registration Succesesfull</h3>';
}
else{
echo '<h3 style="blue">OOPS...Something went wrong here</h3>';
}
}//request POST method
Like I said as form the registration part all is working but as soon as I added the JavaScript validation the whole script stopped working. My biggest problem is that my browser is not showing me any errors so I dont know where I am going wrong
Any help will be much appreciated

Your sendForm function is not triggered.
Code below as your reference, is the right way to trigger submit event via jquery.
jQuery
$(function() {
$('form').submit(function(e) {
e.preventDefault();
var valid;
valid = validateContact()
if(valid ) {
$.ajax({
type: 'POST',
url: "http://facebook.com",
data: {},
dataType: 'json',
success: function() {
alert('success');
},
error: function() {
alert('error');
}
})
}
});
});
function validateContact(){
var valid = true;
var name = document.getElementById("name").value;
var lastname = document.getElementById("lastname").value;
var email = document.getElementById("regEmail").value;
if(name ==''){
document.getElementById("name").style.borderColor="red";
name.value="Please Enter Name";
valid = false;
}
if(lastname ==''){
valid = false;
}
if(email ==''){
valid = false;
}
return valid;
}

I think you need to add a button in your html and call function sendForm() on that button's click event.

Related

jQuery AJAX POST request to PHP must be submitted twice to work

We are building a basic login form that redirects to different pages based on user credentials.
For some reason, we cannot get our login form to return an employee-type value and redirect to the proper page unless we submit the same information twice (the first time, it throws everything into the URL, kind of like a GET request, except that it's writing it to the URL before anything else, even the "#").
We are using Vue.js, but I don't know that it's really relevant to the issue at hand, except that it means the HTML and JS are in the same "component" file.
HTML:
<form class="login-form" id="loginform">
<div class="form-group space">
<label class="float-label" for="username">Username</label>
<input type="username" name="username" id="username" class="form-control" >
</div>
<div class="form-group">
<label class="float-label" for="username">Password</label>
<input type="password" name="password" id="password" class="form-control" >
</div>
<div class="form-group">
<button type="submit" class="btn btn-primary float-right" id="login">Log in</button>
</div>
</form>
JS:
$(function () {
$("#loginform").on('submit', function (e) {
e.preventDefault();
console.log($('#loginform').serialize());
$.ajax({
type: 'post',
url: 'https://fleetr-208415.appspot.com/',
data: $(this).serialize(),
cache: false,
success: function (data) {
var employeeId = data;
console.log(employeeId);
if (employeeId == 1)
{
adminScreen();
}
else if (employeeId == 2)
{
dispatcherScreen();
}
else if (employeeId == 3)
{
truckerScreen();
}
else
{
alert("error");
}
}
});
});
})
function truckerScreen()
{
// similar behavior as an HTTP redirect
window.location.replace("/#/trucker");
}
function dispatcherScreen()
{
window.location.replace("/#/dispatch");
}
function adminScreen()
{
window.location.replace("/#/admin");
}
PHP:
<?php header(“Access-Control-Allow-Origin: *“);
require ‘connection.php’;
$username = $_POST[‘username’];
$password = $_POST[‘password’];
$result = mysqli_query($conn, ‘select name, email, employee_type from employee where employee_id=“‘.$username.‘” and password=“‘.$password.‘“’);
if(mysqli_num_rows($result)==1)
{
while ($row = $result->fetch_assoc())
{
$name = $row[“name”];
$email = $row[“email”];
$employee_type = $row[“employee_type”];
}
echo $employee_type;
}
?>
So if you were submitting username: James, and password: 123, on first submit the URL would become
www.blahblah.net/?username=James&password=123#/login
And then, upon resubmitting the same information, you would be redirected to the proper page. Note that simply reloading the URL with the form information does not have the same effect.
Neither of us has any experience using PHP or AJAX for form submission/user validation, and we are at a total loss as to why this weird error is happening.

Using AJAX when submitting forms

I'm very new to form submission with AJAX and have been following many tutorials on it's use, however I cannot seem to get it working in my current scenario.
I have a modal with a form inside of it linked to a PHP script and some JQuery AJAX.
When i submit the form the page appears white, I'm fairly sure this is because of the conditional logic in my PHP script.
So, where I have $stmt->rowCount() and the conditional logic it returns nothing as the script does nothing at this point.
Can I link this logic to AJAX success or failure or do I have to return a boolean from my script?
I know this is probably considered a silly question but some clarity would be of great use.
Form
<form id="userForm" method="post" action="test/process_data.php">
<div class="form-group">
<label for="email">First name:</label>
<input type="text" class="form-control" name="forename" id="forename" placeholder="E.g John" required>
</div>
<div class="form-group">
<label for="email">Surname:</label>
<input type="text" class="form-control" name="surname" id="surname" placeholder="E.g Smith" required>
</div>
<div class="form-group">
<label for="email">Email:</label>
<input type="email" class="form-control" name="email" id="email" placeholder="someone#example.com">
</div>
<div class="form-group">
<label for="company">Company:</label>
<input type="text" class="form-control" name="company" id="company" placeholder="Company name">
</div>
<button type="submit" class="btn btn-primary">Submit</button>
Just take me to the partner
</form>
AJAX Script
<script>
$("#userForm").submit(function(e) {
var forename = $('#forename').val();
var surname = $('#surname').val();
var email = $('#email').val();
var company = $('#company').val();
$.ajax({
url: "process_data.php",
type: "POST",
data: {
"forename" : forename,
"surname" : surname,
"email" : email,
"company" : company
},
success: function(data){
$("#forename").val('');
$("#surname").val('');
$("#email").val('');
$("#company").val('');
}
});
e.preventDefault(); // avoid to execute the actual submit of the form.
}
</script>
PHP Script to handle data
if (empty($_POST["forename"]) ||
empty($_POST["surname"]) ||
empty($_POST["email"]) ||
empty($_POST["company"]))
{
}
else{
$forename = $_POST['forename'];
$surname = $_POST['surname'];
$email_address = $_POST['email'];
$company_name = $_POST['company'];
$id = rand();
$date_time = date('Y-m-d');
try
{
// Construct the SQL to add a book to the database
$sql = "INSERT INTO user_data (forename, surname, email_address, company_name, id, date_time)
VALUES (:forename, :surname, :email_address, :company_name, :id, :date_time)";
// Prepare the SQL and bind parameters
$stmt = $conn->prepare($sql);
$stmt->bindParam(':forename', $forename);
$stmt->bindParam(':surname', $surname);
$stmt->bindParam(':email_address', $email_address);
$stmt->bindParam(':company_name', $company_name);
$stmt->bindParam(':id', $id);
$stmt->bindParam(':date_time', $date_time);
$stmt->execute();
// If the statement affected the database
if ($stmt->rowCount() > 0)
{
}
else{
}
} catch(PDOException $e){
echo "Error: " . $e->getMessage();
}
}
Use serialize() method on the form to define the data property in your ajax call. Also added error handling.
$.ajax({
url: "process_data.php",
type: "POST",
data: $("#userForm").serialize(),
success: function(data){
//Successful
},
error: function (XMLHttpRequest, textStatus, errorThrown)
{
if (!window.console) console = { log: function () { } };
console.log(JSON.stringify(XMLHttpRequest), textStatus, errorThrown);
}
});
Use preventDefault(); before sending ajax request. Now when the form is done submitting you can do like this.
<script>
$("#userForm").submit(function(e) {
var forename = $('#forename').val();
var surname = $('#surname').val();
var email = $('#email').val();
var company = $('#company').val();
e.preventDefault(); // avoid to execute the actual submit of the form.
$.ajax({
url: "process_data.php",
type: "POST",
data: {
"forename" : forename,
"surname" : surname,
"email" : email,
"company" : company
},
success: function(data){
}
});
$("#userForm").fadeOut(800, function()
{
$(this)[0].reset();
}).fadeIn(800);
}
</script>

creating a validation script for a submission form

I have created a submission form using Expression engine's plugin freeform, everything is working in terms of submission, the only issue i am having is the valuation side of things.
Is there a way to validate my script before submission, i.e pick up things as unfilled fields, incorrect emails etc..
below is a snippet of my code.
JQUERY
var form = $('#ajax-contact');
var formMessages = $('#form-messages');
$(form).submit(function(e) {
e.preventDefault();
var formData = $(form).serialize();
// Submit the form using AJAX.
$.ajax({
type: 'POST',
url: $(form).attr('action'),
data: formData
})
.done(function(response) {
if (response.success) {
formMessages.removeClass('error').addClass('success').text("Thank you for submitting your details");
$('.valFields').val("");
} else {
formMessages.removeClass("success").addClass("error").text("Oops, Please check your details");
}
})
.fail(function(data) {
// Make sure that the formMessages div has the 'error' class.
$(formMessages).removeClass('success');
$(formMessages).addClass('error');
// Set the message text.
if (data.responseText !== '') {
$(formMessages).text(data.responseText);
} else {
$(formMessages).text('Oops! An error occured and your message could not be sent.');
}
});
})
});
HTML
<div id="form-messages">
{exp:freeform:form
form_id="1"
admin_notify="myemail#.me.com"
form:class="main-contact submit-fade ajax-form"
form:id="ajax-contact"
}
<ul class="small-block-grid-2 medium-block-grid-2 hide-form">
<li>
<label for="name">Name</label>
{freeform:field:first_name
attr:class="form-control valFields"
attr:placeholder="First Name"
attr:class="required"
}
</li>
<li>
<label for="email">Email</label>
{freeform:field:email
attr:class="form-control valFields"
attr:placeholder="Email"
attr:class="required"
}
</li>
</ul>
<input type="submit" class="btn btn-success">
{/exp:freeform:form}
</div>
</div>
</div>
Validation of fields can done calling a function
Call Validate function onSubmit action and if successful perform the submission of form using AJAX.
Example:
<script>
$(form).submit(function(e) {
e.preventDefault();
var check = validate();
if(check){
var formData = $(form).serialize();
..
//form sumit using AJAX
..
}
function validate()
{
if( document.myForm.Name.value == "" )
{
alert( "Please provide your name!" );
document.myForm.Name.focus() ;
return false;
}
if( document.myForm.EMail.value == "" )
{
alert( "Please provide your Email!" );
document.myForm.EMail.focus() ;
return false;
}
return true;
}
</script>
The better way of doing this is putting types in inputs
<ul class="small-block-grid-2 medium-block-grid-2 hide-form">
<li>
<label for="name">Name</label>
{freeform:field:first_name
attr:class="form-control valFields"
attr:placeholder="First Name"
attr:required="required"
}
</li>
<li>
<label for="email">Email</label>
{freeform:field:email
attr:class="form-control valFields"
attr:placeholder="Email"
attr:required="required",
attr:type="email"
}
</li>
</ul>
It will not only make sure that the fields are not left empty but also will check the valid email type.

Login form using PHP and AJAX

I am simply trying to log in on a popup log in box. I used AJAX to check whether log in is successful or not. If it is successful move to header location otherwise Give an error.
Code look like this:
<script>
$(document).ready(function () {
$('#login').click(function () {
var email = $("#email").val();
var pass = $("#pass").val();
var dataString = 'email=' + email + '&pass=' + pass;
if ($.trim(email).length > 0 && $.trim(pass).length > 0) {
$.ajax({
type: "POST",
url: "ajaxlogin.php",
data: dataString,
cache: false,
success: function (data) {
if (data) {
$("body").load("index.php").hide().fadeIn(1500).delay(6000);
//or
window.location.href = "index.php";
}
else {
$("#login").val('Login')
$("#error").html("<span style='color:#cc0000'>Error:</span> Invalid username and password. ");
}
}
});
}
return false;
});
});
</script>
Form:
<div class="user_login">
<form action="" method="post">
<label>Email / Username</label>
<input type="email" Placeholder="Email-id" name="email" Required="required" id="email"/>
<br />
<label>Password</label>
<input type="password" Placeholder="Password" name="pass" Required="required" id="pass"/>
<br />
<div class="checkbox">
<input id="remember" type="checkbox" />
<label for="remember">Remember me on this computer</label>
</div>
<div class="action_btns">
<div class="one_half"><i class="fa fa-angle-double-left"></i> Back</div>
<div class="xyx"><input type="submit" value="Login" name="submitm" id="login"/></div>
<div id="error"></div>
</div>
</form>
Forgot password?
</div>
and php file is separate named as ajaxlogin.php:
include('includes/db.php');
if (isset($_POST['email']) && isset($_POST['pass'])) {
$pass = $_POST['pass'];
$email = $_POST['email'];
$query = "SELECT * FROM login WHERE email='$email' AND BINARY pass=BINARY '$pass'";
$result = mysql_query($query);
if (mysql_num_rows($result) > 0) {
$_SESSION['user'] = $email;
}
}
Both Script and form are on same page. Output that i am currently getting is Error message Both for right and wrong Username/Password Match. But if i delete "return false;" from script it moves to header location without log in.
try this script,
$(document).ready(function()
{
$('#login').click(function()
{
var email = $("#email").val();
var pass = $("#pass").val();
if ($.trim(email).length > 0 && $.trim(pass).length > 0)
{
$.ajax({
type: "POST",
url: "ajaxlogin.php",
data: {email:email,pass:pass},
cache: false,
success: function(data) {
if (data)
{
$("body").load("index.php").hide().fadeIn(1500).delay(6000);
window.location.href = "index.php";
}
else
{
$("#login").val('Login')
$("#error").html("<span style='color:#cc0000'>Error:</span> Invalid username and password. ");
}
}
});
}
return false;
});
});
Looks like you are not returning any data from ajaxlogin.php
so the success function always takes control to else and throws you an error message on the screen.

Validate input form using jquery with reCAPTCHA

I have a comment form which insert data to a database upon submitting. Following is the code;
function reloadRecaptcha() {
var publicKey = "*************************************";
var div = "recap";
Recaptcha.create(publicKey,div,{theme: "white"});
return false;
}
function validateForm() {
var x=document.forms["cmnts"]["name"].value;
if (x==null || x=="") {
jAlert('Please enter your name', 'Error');
return false;
}
var x=document.forms["cmnts"]["email"].value;
var atpos=x.indexOf("#");
var dotpos=x.lastIndexOf(".");
if (atpos<1 || dotpos<atpos+2 || dotpos+2>=x.length) {
jAlert('Please enter a valid email address', 'Error');
return false;
}
var x=document.forms["cmnts"]["comment"].value;
if (x==null || x=="") {
jAlert('Please enter a comment', 'Error');
return false;
}
var challenge = Recaptcha.get_challenge();
var response = Recaptcha.get_response();
$.ajax({
type: "POST",
url: "includes/valrecaptcha.php",
async: false,
data: {
challenge: challenge,
response: response
},
success: function(resp) {
if(resp == "false") {
jAlert('Please enter captcha words correctly', 'Error');
reloadRecaptcha();
}
}
});
}
Everything (such as form validating works fine except when I hit the submit button, the comment is posted no matter the reCAPTCHA is correct or not. Right before the page starts navigating, I see the alert message. I'm using jAlert to display alert messages. Following is the form;
<h4>Leave your comment</h4>
<form action="blog?post=".$_GET["post"]."#comments" onsubmit="return validateForm();" name="cmnts" method="post">
<div class="form_row">
<label>Name</label><br />
<input type="text" class="tbox" name="name" title="Type your name"/>
</div>
<div class="form_row">
<label>Email (not visible to others)</label><br />
<input type="text" class="tbox" name="email" title="Type your email" />
</div>
<div class="form_row">
<label>Comment</label><br />
<textarea name="comment" class="tbox" rows="6" title="Type your comment" ></textarea>
<p>You may use following HTML tags and attributes: <b> <cite> <del> <i> <u></p>
</div>
<div class="form_row" style="height:80px;">
<label>Captcha</label><br />
<div id="recap"></div>
<p>I must make sure that you're <i>not</i> a spammer or a bot</p>
<div style="clear:both;">
</div>
<input value="Comment" id="submit" name="submit" class="submit_btn float_l" type="submit">
</form>
The <body> tag has an onload event return reloadRecaptcha();
So why doesn't the form get submitted before validating the reCAPTCHA?
This happens because validateForm() does not return anything from the ajax call. You should have a variable like isCaptchaValidated, and set that inside the success() of ajax, and then return that variable after the ajax like below:
var isCaptchaValidated = false;
$.ajax({
type: "POST",
url: "includes/valrecaptcha.php",
async: false,
data: {
challenge: challenge,
response: response
},
success: function(resp) {
if(resp == "false") {
jAlert('Please enter captcha words correctly', 'Error');
reloadRecaptcha();
} else {
isCaptchaValidated = true;
}
}
});
return isCaptchaValidated;
By the way, ajax means Asynchronous JavaScript and XML, so I would go against setting async: false.

Categories