Remote Validation in jQuery not validating - ajax

This form will INSERT both an email and password into my MYSQL db
First, I am trying to validate an email remotely to make sure it does not exists, and also that
the Pswd and Pswd2 are equal.
the script writes to the db, but the validation is not working. I am new to JQ and Ajax so any help would be apprecated.
Thanks.
FORM:
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.0.1/jquery.mobile-1.0.1.min.css" />
<script src="http://code.jquery.com/jquery-1.6.4.min.js"></script>
<script src="http://code.jquery.com/mobile/1.0.1/jquery.mobile-1.0.1.min.js"></script>
<script src="jquery.validate.js" type="text/javascript"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.9/additional-methods.min.js"></script>
...
<div data-role="content">
<form id="AddUser" class="ui-body ui-body-a ui-corner-all" data-ajax="true" >
<fieldset>
<div data-role="fieldcontain">
<label for="Email">Email Address:</label>
<input id="Email" type="email" />
<label for="Pswd">Password:</label>
<input id="Pswd" type="password" />
<label for="Pswd2">Confirm Password:</label>
<input id="Pswd2" type="password" />
</div>
<button type="submit" id="submit" data-theme="b" name="submit" value="submit-value">Submit</button>
</fieldset>
</form>
</div>
...
below is the js inside the document:
<script>
$(document).ready(function() {
var validator =
$('#AddUser').validate({
rules: {
Pswd: {
required: true,
},
Pswd2: {
required: true,
equalTo: "#Pswd"
},
Email: {
required: true,
email: true,
remote: "process/ValidateEmail.php"
}
},
messages: {
Pswd: {
required: "Provide a password",
},
Pswd2: {
required: "Repeat your password",
equalTo: "Enter the same password as above"
},
Email: {
required: "Not A Valid Email Address",
remote: "already in use"
}
}
}); // end var validator
if (validator)
{
$("#AddUser").submit(function(){
//make Variables
var emailVar =$('input[id=Email]').val();
var pswdVar = $('input[id=Pswd]').val();
var pswdconfirm = $('input[id=Pswd2]').val();
var querystring = "Email="+emailVar+"&Pswd="+pswdVar;
$.post("process/AddUser.php",querystring);
}); //end submit()
}; // end if validator
}); //end ready()
</script>
the Validator file (ValidateEmail.php)
<?php
$UserEmail = $_POST["Email"];
include "connection.php";
$sqlEmail= mysql_query("Select EmailAddress from USERS where EmailAddress='$UserEmail'");
$EmailCheck=mysql_fetch_array($sqlEmail);
if (mysql_num_rows($EmailCheck) > 0) {
echo json_encode(true);
} else {
echo json_encode(false);
}
?>

I went back to the code after some research and found it riddled with errors in both the js and the php validation:
<script>
$(document).ready(function()
{
var validator = $("#AddUser").validate({
rules: {
Email: {
required: true,
email: true,
remote: "process/ValidateEmail.php"
},
Pswd: {
required: true,
},
Pswd2: {
required: true,
equalTo: "#Pswd"
},
},
messages: {
Pswd: {
required: "Provide a password",
},
Pswd2: {
required: "Repeat your password",
equalTo: "Password Mismatch"
},
Email: {
required: "Invalid Email",
remote: jQuery.format("{0} is already used")
}
},
// the errorPlacement has to take the table layout into account
errorPlacement: function(error, element) {
error.appendTo(element.parent().next());
},
// specifying a submitHandler prevents the default submit, good for the demo
submitHandler: function() {
//make Variables
var emailVar =$('input[id=Email]').val();
var pswdVar = $('input[id=Pswd]').val();
var pswdconfirm = $('input[id=Pswd2]').val();
var querystring = "Email="+emailVar+"&Pswd="+pswdVar;
$.post("process/AddUser.php",querystring);
$('#AddUser').clearForm();
return false;
},
// set this class to error-labels to indicate valid fields
success:
function(label) {
label.html(" ").addClass("checked");
}
});
});
</script>

email: {
required: true,
email: true,
remote: {
url: "check-email.php",
type: "post",
data: {
email: function() {
return $("[name='email']").val();
}
}
}
},
and the php must look like this:
$email= $_POST['email'];
include 'connect.php';
$email = trim(mysql_real_escape_string($email));
$query = mysql_query("SELECT COUNT(id) FROM users WHERE email = '$email'") or die(mysql_error());
echo (mysql_result($query, 0) == 1) ? 'false' : 'true';
be careful not to echo just false or true it must be echoed like this 'false' or true

Related

Error on my nuxt app TypeError: Cannot use 'in' operator to search for 'meta.token'

I'm building a login page and to pass the token from the backend I modify my nuxt config file with this strategy:
auth: {
strategies: {
local: {
endpoints: {
login: { url: '/auth/login', method: 'post', propertyName: 'meta.token' },
logout: { url: '/auth/logout', method: 'post' },
}
}
}
},
my login page:
<div>
<div>
<form action="#" #submit.prevent="login">
<b-form-input
v-model="form.name"
id="input-default"
placeholder="Enter Username"
type="text"
></b-form-input>
<b-form-input
v-model="form.password"
placeholder="Enter Password"
type="password"
></b-form-input>
<b-button type="submit" variant="success">Login</b-button>
</form>
</div>
</div>
</template>
<script>
export default {
data() {
return {
form: {
name: "",
password: "",
},
};
},
methods: {
async login() {
try {
await this.$auth.loginWith('local', {
data: this.form,
});
this.$router.push({path : "index"});
} catch (error) {
this.messageError = error
}
},
},
};
</script>
Server-side I've added a custom response that returns login data in this way
{
"success": true,
"message": "",
"code": 200,
"data": {
"token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJodHRwOi8vbG9jYWxob3N0OjgwMDAvYXBpL2F1dGgvbG9naW4iLCJpYXQiOjE2NzExMzA2NDUsImV4cCI6MTY3MTEzNDI0NSwibmJmIjoxNjcxMTMwNjQ1LCJqdGkiOiJQcXc1bHNmY1JWN2dLdVZUIiwic3ViIjoiMyIsInBydiI6IjIzYmQ1Yzg5NDlmNjAwYWRiMzllNzAxYzQwMDg3MmRiN2E1OTc2ZjcifQ.0IB-Efk3RaZY4NzHRIQS0CmH95KKa4-vF3dNJG2fNBg"
}
}
I receive the error
TypeError: Cannot use 'in' operator to search for 'meta.token'
OP solved that one by fixing a proxy issue. Was probably a typo or something similar.

How to submit form with Ajax and Jquery Validation?

I am trying to submit a from with Ajax and use query validation plugin to validate it . I write code below :
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src="jquery.validate.js"></script>
</head>
<body>
<form id="myForm">
<input type="text" name="name" />
<br/>
<input type="text" name="school" />
<br/>
<input type="submit" />
</form>
<div id="result"></div>
<script>
$(document).ready(function () {
$("#myForm").validate({
onkeyup: false,
rules: {
name: {
required: true,
minlength: 5
},
school: {
required: true,
minlength: 5
}
}
});
event.preventDefault();
$("#result").html('');
var values = $(this).serialize();
$("#myForm").ajaxForm({
url: "add_admin.php",
type: "post",
data: values,
beforeSubmit: function () {
return $("#myForm").valid();
},
success: function(){
//alert("success");
$("#result").html('Submitted successfully');
},
error:function(){
// alert("failure");
$("#result").html('There is error while submit');
}
});
});
</script>
</body>
but it didn't work . Made I any mistake here ?
can any one help me ?
some text some text some text some text some text
Update : Use following option as it works on all circumstances giving you power of ajax
JSFiddle here
Check in your NET tab under Inspect element or Firebug
$("#myForm").validate({
rules: {
school: {
required: true,
minlength: 5
}
},
submitHandler: function(form) {
//Your code for AJAX starts
jQuery.ajax({
url:'ajax.php',
type: "post",
data: $(form).serialize(),
success: function(){
//alert("success");
$("#result").html('Submitted successfully');
},
error:function(){
// alert("failure");
$("#result").html('There is error while submit');
}
//Your code for AJAX Ends
});
}
});
Bottomline -> Use jQuery validate's own mechansim of posting form via AJAX inside submitHandler.
This might help you...
<form id="myForm">
<input type="text" name="name" />
<br />
<input type="text" name="school" />
<br />
<input type="submit" id="BTNTest" />
</form>
<div id="result"></div>
<script>
$(document).ready(function () {
$("#myForm").validate({
onkeyup: false,
rules: {
name: {
required: true,
minlength: 5
},
school: {
required: true,
minlength: 5
}
}
});
event.preventDefault();
$("#result").html('');
var values = $(this).serialize();
$(document).on('click', '#BTNTest', function () {
$.ajax({
url: "add_admin.php",
type: "post",
data: values,
beforeSubmit: function () {
return $("#myForm").valid();
},
success: function () {
//alert("success");
$("#result").html('Submitted successfully');
},
error: function () {
// alert("failure");
$("#result").html('There is error while submit');
}
});
});
});
</script>

Inserting a general validation alert using KnockoutJS validation

I'd looking for the most effective way of inserting a general validation alert "Please check your submission" to be positioned above the fieldset, instead of in an alert pop-up as coded below.
http://jsfiddle.net/Nz38D/3/
HTML:
<script id="customMessageTemplate" type="text/html">
<em class="customMessage" data-bind='validationMessage: field'></em>
</script>
<fieldset>
<legend>Details</legend>
<label>First name:
<input data-bind='value: firstName' />
</label>
<label>Last name:
<input data-bind='value: lastName' />
</label>
<div data-bind='validationOptions: { messageTemplate: "customMessageTemplate" }'>
<label>Email:
<input data-bind='value: emailAddress' required pattern="#" />
</label>
</fieldset>
<br>
<button type="button" data-bind='click: submit'>Submit</button>
<br>
<br> <span data-bind='text: errors().length'></span> errors
JS:
ko.validation.rules.pattern.message = 'Invalid.';
ko.validation.configure({
decorateElement: true,
registerExtenders: true,
messagesOnModified: true,
insertMessages: true,
parseInputAttributes: true,
messageTemplate: null
});
var viewModel = function() {
this.firstName = ko.observable().extend({
minLength: 2,
maxLength: 10
});
this.lastName = ko.observable().extend({
required: true
});
this.emailAddress = ko.observable().extend({ // custom message
required: {
message: 'Enter your email address.'
}
});
this.submit = function () {
if (this.errors().length == 0) {
alert('Thank you.');
} else {
alert('Please check your submission.');
this.errors.showAllMessages();
}
};
this.errors = ko.validation.group(this);
};
ko.applyBindings(new viewModel());
I inserted a virtual element to hold the validation summary message and bound its display to an observable in the click function: http://jsfiddle.net/sx42q/2/
HTML:
<!-- ko if: displayAlert -->
<p class="customMessage" data-bind="text: validationSummary"></p> <br />
<!-- /ko -->
JS:
this.validationSummary = ko.observable("Complete missing fields below:");
this.displayAlert = ko.observable(false);
this.submit = function () {
if (this.errors().length == 0) {
alert('Thank you.');
} else {
this.displayAlert(true);
this.errors.showAllMessages();
}

Ajax Contact form validation and submit

I'm trying to make a HTML contact form. Here's my code
`Get in Touch
<p class="success-sending-message">Thank you, your message has been sent!</p>
<p class="error-sending-message">There has been an error, please try again.</p>
<div id="contact-form">
<form action="" id="contactForm" class="styled" method="post">
<label for="contact_name">Name</label>
<input type="text" tabindex="3" id="contact_name" name="contact_name" value="" class="requiredField textbox" />
<label for="contact_email">Email</label>
<input type="text" tabindex="4" id="contact_email" name="contact_email" value="" class="requiredField email textbox" />
<label for="contact_subject">Subject</label>
<input type="text" tabindex="5" id="contact_subject" name="contact_subject" value="" class="requiredField textbox" />
<label for="contact_message">Your Message</label>
<div class="textarea-wrap">
<textarea cols="65" rows="9" tabindex="6" id="contact_message" name="contact_message" class="requiredField"></textarea>
</div>
<div class="form-section">
<button class="button" tabindex="7" type="submit" id="born-submit" name="born-submit">Send Message</button>
<input type="hidden" name="submitted" id="submitted" value="true" />
<span class="sending-message"><img src="css/images/loading-light.gif" /> Sending...</span>
</div>
</form>
</div>`
And here's my validation script
$(window).load(function() {
/* Ajax Contact form validation and submit */
jQuery('form#contactForm').submit(function() {
jQuery(this).find('.error').remove();
var hasError = false;
jQuery(this).find('.requiredField').each(function() {
if(jQuery.trim(jQuery(this).val()) == '') {
if (jQuery(this).is('textarea')){
jQuery(this).parent().addClass('input-error');
} else {
jQuery(this).addClass('input-error');
}
hasError = true;
} else if(jQuery(this).hasClass('email')) {
var emailReg = /^[a-zA-Z0-9._-]+#[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;
if(!emailReg.test(jQuery.trim(jQuery(this).val()))) {
jQuery(this).addClass('input-error');
hasError = true;
}
}
});
if(!hasError) {
jQuery(this).find('#born-submit').fadeOut('normal', function() {
jQuery(this).parent().parent().find('.sending-message').show('normal');
});
var formInput = jQuery(this).serialize();
var contactForm = jQuery(this);
jQuery.ajax({
type: "POST",
url: jQuery(this).attr('action'),
data: formInput,
success: function(data){
contactForm.parent().fadeOut("normal", function() {
jQuery(this).prev().prev().show('normal'); // Show success message
});
},
error: function(data){
contactForm.parent().fadeOut("normal", function() {
jQuery(this).prev().show('normal'); // Show error message
});
}
});
}
return false;
});
jQuery('.requiredField').blur(function() {
if(jQuery.trim(jQuery(this).val()) != '' && !jQuery(this).hasClass('email')) {
if (jQuery(this).is('textarea')){
jQuery(this).parent().removeClass('input-error');
} else {
jQuery(this).removeClass('input-error');
}
} else {
if (jQuery(this).is('textarea')){
jQuery(this).parent().addClass('input-error');
} else {
jQuery(this).addClass('input-error');
}
}
});
jQuery('.email').blur(function() {
emailReg = /^[a-zA-Z0-9._-]+#[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;
if(emailReg.test(jQuery.trim(jQuery(this).val())) && jQuery(this).val() != '') {
jQuery(this).removeClass('input-error');
} else {
jQuery(this).addClass('input-error');
}
});
jQuery('.requiredField, .email').focus(function(){
if (jQuery(this).is('textarea')){
jQuery(this).parent().removeClass('input-error');
} else {
jQuery(this).removeClass('input-error');
}
});
});
My form is working properly, After filling details It is showing me "Thank you, your message has been sent!" But where is this message going, I don't have any of the process.php file and all. I want that email should be send to my email id.
Bonjour ... Look in the firebug or chrome developper tools console to see the post trace.
In your php file, you can put echos or var_dump to be sure all it's ok.
Another thing ... the form action is empty.
Currently there's no where it is going. Give where it needs to go in the action="" attribute of the <form>. And also, in the actioned URL, typically, a PHP file, give this code:
<?php
if (count($_POST))
{
$name = $_POST["contact_name"];
$email = $_POST["contact_email"];
$subject = $_POST["contact_subject"];
$message = $_POST["contact_message"];
$mail = "Name: $name\nEmail: $email\nSubject: $subject\nMessage: $message";
if (mail("mymail#domain.com", "New Mail from Contact Form", $mail))
die ("OK");
else
die ("Fail");
}
?>
Also, you need to make a small correction in your JavaScript AJAX Call. Replace this way:
jQuery.ajax({
type: "POST",
url: jQuery(this).attr('action'),
data: formInput,
success: function(data){
if (data == "OK")
contactForm.parent().fadeOut("normal", function() {
jQuery(this).prev().prev().show('normal'); // Show success message
});
else
alert ("Message not sent!");
},
error: function(data){
contactForm.parent().fadeOut("normal", function() {
jQuery(this).prev().show('normal'); // Show error message
});
}
});
Test if your server supports SMTP through PHP Script
Create a small file, which has this content, say mail.php:
<?php
var_dump(mail("yourmail#gmail.com", "Testing Message", "This mail was sent from PHP Script."));
?>
And try to access the file and see what you are getting. Please update the same in your question.

Ajax submit after validation (jQuery Mobile + Validator)

I'm having trouble getting this to work. It validates the fields as expected, but no matter what I try, I can't properly hook the submit.
Here's my form:
<form action="" id="m-frm-contact_us" class="m-contact_submit" method="post" data-ajax="false">
<input type="text" name="firstName" placeholder="FIRST NAME" title="" id="first" class="contact full required" minlength="2" maxlength="36" />
<input type="text" name="lastName" placeholder="LAST NAME" id="last" class="contact full required" minlength="2" maxlength="36" />
<input type="email" name="mail" placeholder="E-MAIL ADDRESS" id="mail" class="contact full required email" />
<button type="submit" name="submit_contact" value="clicked">Submit</button>
</form>
My JS:
$(document).ready(function(){
$.validator.addMethod(
'placeholder', function(value, element) {
return value != $(element).attr("placeholder");
}, 'This field is required.'
);
$("#m-frm-contact_us").validate({
rules: {
firstName: {
required: true,
minlength: 5,
placeholder: true
},
lastName: {
required: true,
minLength: 5,
placeholder: true
},
mail: {
required: true,
email: true,
placeholder: true
}
},
messages: {
firstName: "First name is required.",
lastName: "Last name is required.",
email: "Valid email address is required."
},
submitHandler: function(form) {
console.log('submitHandler fired.');
contact.submit();
return false;
}
});
$('#m-frm-contact_us').submit(function(e){
console.log('Submit event fired.');
e.preventDefault();
return false;
});
var contact = {
submit : function(){
console.log('Form is being submitted.');
}
};
});
The only thing I get in my console is 'Submit event fired.', called on form submit. Despite my efforts, the form always tries to post to itself, reloading the page.
I want to execute this code on submit:
var contact = {
submit : function(){
console.log('Form is being submitted.');
var _this = this,
post = $.post("/path/to/submit.php", $("#m-frm-contact_us").serialize(), function(response){
try{
if(response==1) {
_this.passed();
} else {
_this.error();
}
}
catch(e){
if(typeof e == 'string') console.log(e);
_this.error();
}
});
},
error : function(){ $.mobile.changePage("#error"); },
passed : function(){ $.mobile.changePage("#passed"); }
}
What am I missing?
I rebuilt the JS, and was able to get this working. Here's the code, in case anyone experiences a similar issue:
Form:
<form action="" method="post" id="m-frm-contact_us" novalidate="novalidate">
<input type="text" name="firstName" placeholder="FIRST NAME" title="" id="first" class="contact full required placeholder noSpecial" minlength="2" maxlength="36">
<input type="text" name="lastName" placeholder="LAST NAME" id="last" class="contact full required placeholder" minlength="2" maxlength="36">
<input type="email" name="mail" placeholder="E-MAIL ADDRESS" id="mail" class="contact full required email">
<button type="submit" name="submit_contact" value="clicked">Submit</button>
</form>
JS:
$.validator.addMethod('noPlaceholder', function(value, element) {
return value !== element.defaultValue;
}, 'This field is required.');
$.validator.addMethod(
'placeholder', function(value, element) {
return value != $(element).attr("placeholder");
}, 'This field is required.'
);
$.validator.addMethod("regex", function(value, element, regexp) {
var check = false;
var re = new RegExp(regexp);
return this.optional(element) || re.test(value);
}, "No special Characters allowed here. Use only upper and lowercase letters (A through Z; a through z)");
$('#m-frm-contact_us').submit(function(event) {
event.preventDefault();
if($(this).validate({
rules : {
first_name : {
required : true,
maxlength : 36,
regex : /^[A-Za-z\s`'"\\-]+$/
},
last_name : {
required : true,
maxlength : 36,
regex : /^[A-Za-z\s`'"\\-]+$/
}
}
}).form()) {
var $form = $(this), formData = {
firstName : $form.find('#first').val(),
lastName : $form.find('#last').val(),
mail : $form.find('#mail').val()
};
$.post('/path/to/submit.php', formData, function(response) {
if(response == 1) {
$.mobile.changePage("#passed");
} else {
$.mobile.changePage("#error");
}
})
};
return false;
})

Resources