How to remove AJAX from jQuery validation plugin function - javascript

This is going to be a stupid question but I have spent an inordinate amount of time trying to remove the AJAX part from the jQuery validation plugin function below but still have the validation work. Suffice to say I haven't succeeded.
$(document).ready(function(){
$("#myform").validate({
debug: false,
rules: {
group: {required: true},
},
messages: {
group: {required: " Choose a group."},
},
submitHandler: function(form) {
$('#results').html('Loading...');
$.post('', $("#myform").serialize(), function(data) {
$('#results').html(data);
});
}
});
});
So yeah, I'm dumb. Can anyone help me out?

When you send the object back, send it as a JSON object.
Here's an example where we're going to use the serialized elements, conditionalize some data, and then send something back with our new page.
<?php
$name = $_POST['name'];
$email = $_POST['email'];
$phone = $_POST['phone'];
if(isset($name) && isset($email) && isset($phone)){
return json_encode(array('filled' => 'yes', 'loc' => 'newpage.php'));
}
?>
Then in the validator, we can parse data.loc to the window.location to mimic the redirect.
$(document).ready(function(){
$("#myform").validate({
debug: false,
rules: {
group: {required: true},
},
messages: {
group: {required: " Choose a group."},
},
submitHandler: function(form) {
$('#results').html('Loading...');
$.post('', $("#myform").serialize(), function(data) {
if(data.filled == 'yes'){
window.location = data.loc;
}
});
}
});
});

You just need to replace the submitHandler function!
submitHandler: function(form) {
$('#results').html('Loading...');
// $.post('', $("#myform").serialize(), function(data) {
// $('#results').html(data);
// });
}
And after calling .validate(), call the .valid() function on #myform this way:
$('#myform').valid();
Just make sure you are removing the default action of submit on the form by adding this:
<form onsubmit="if (!$(this).valid()) return false;">
Explanation: This doesn't submit the form when it is not valid and shows the errors. If the form is valid, this function submits as a normal form submit.
But why do you wanna do that? What else you wanna do?

Related

What is the purpose of this function's parameter?

I would like to use a validate js plugin for a form (contact form with no refresh). I found this code below, where its author uses submitHandler key to send e-mails via AJAX and PHP. As the value there is a function function(form) { ... }. Could You tell me what is the purpose of the form parameter inside function(form)? The author doesn't even use it inside that function.
JS CODE:
$().ready(function() {
// validate the comment form when it is submitted.
$("#actualForm").validate({
focusInvalid: false,
onkeyup: true,
rules: {
// simple rule, converted to {required:true}
name: "required",
comment: "required",
email: {
required: true,
email: true
},
},
submitHandler: function(form) {
var name = $('input[name="name"]').val();
var email = $('input[name="email"]').val();
var comment = $('input[name="comment"]').val();
var params = {
"name": name,
"email": email,
"comment": comment,
};
console.log(data);debugger;
$.ajax({
url: 'email.php',
data: params,
type: 'POST',
dataType: json,
success: function (data) {
if (data.status) {
//Give success log to user
} else {
//Do something
}
}
});
}

unable to send data via this.serialize

I am using following function to validate and send data to the php server:
$(document).ready(function () {
$(function() {
// Setup form validation on the #register-form element
$("#register_form").validate({
// Specify the validation rules
rules: {
register_username: "required",
register_password: "required",
register_email: {
required: true,
email: true
},
register_confirm_password: {
required: true,
equalTo: '#register_password'
},
},
// Specify the validation error messages
messages: {
register_username: "Please enter your username",
register_password: "Please enter your password",
register_confirm_password: {
required: "Please provide a password",
equalTo:"Please enter password same as above."
},
register_email: "Please enter a valid email address",
},
submitHandler: function(form) {
var pdata = $(this).serialize();
alert(pdata);
$.ajax({
type: 'POST',
url: 'http://localhost/quiz/index.php/signin',
data: $(this).serialize(),
dataType : 'json',
success: function(data) {
if (data.success){
console.log("Form is submitted.data is" + data.success);
$.each(data, function() {
$.each(this, function(k, v) {
console.log("key; " + k);
console.log("value; " + v);
});
});
}
else
{
console.log("The data returned is:" + data.success);
}
},
error: function(jqXHR, textStatus, errorThrown) {
console.log(textStatus, errorThrown);
}
});
return false;
},
});
});
});
All the validation works, but the issue is with the line:
var pdata = $(this).serialize();
I am getting empty pdata:
alert(pdata);
I don't know why the data is not serialized here. Please help me to solve this.
Don't serialize $( this )
Try serializing the form instead.
$( "#register_form" ).serialize();
$(this) isn't what you think it is anymore. It's not #register_form, but instead the submitHandler function.
If you do console.log(pdata) you should see the function definition in your console.
The scope of the submitHandler function is not the form element, so this is not pointing to the element you require. It does however provide you with a parameter, which you've named form, that you can use instead, like this:
submitHandler: function(form) {
$.ajax({
type: 'POST',
url: 'http://localhost/quiz/index.php/signin',
data: $(form).serialize(),
// your code...

Jquery validator module and function call after success

First I don't have much experience with javascript and jquery :) I am just trying to find a quick way to connect jquery email validator module with a function that checks recaptcha. Here is my code:
jQuery.validator.setDefaults({
debug: true,
success: "valid"
});
$( "#myform" ).validate({
rules: {
field: {
required: true,
email: true
}
}
});
Works fine! Inputs are validated.
Now after validation I need two things: First I need to call recapVerify(), after recaptcha gets validated I need to submit my form. This is the example I use: email method. I know I need to use submitHandler now but I can't figure out where and how?
Btw. this is recapVerify() function that I want to use:
function recapVerify(){
$.ajax({
type:'post',
url: 'captcha_check.php',
data: {
recaptcha_challenge_field:$('#recaptcha_challenge_field').val(),
recaptcha_response_field:$('#recaptcha_response_field').val()
}
}).done(function(data, textStatus, jqXHR){
if (data == 'success'){
$('#err').addClass('hidden');
//document.forms[0].submit(); // uncomment this line to submit your form
alert('Success, the form and reCAPTCHA validated, your form was submitted');
} else {
$('#err').removeClass('hidden');
}
}).fail(function(jqXHR,textStatus,errorThrown){
console.log('recaptcha or service failure');
});
}
use submitHandler on your jquery validate function. Debug is not needed. In essence this is the javascript you need.
$(document).ready(function(){
$("#test-form").validate({
rules: {
name: {
required: true,
},
email : {
required : true,
email : true
}
},
submitHandler : recaptchaVerify
});
});
function recaptchaVerify(form){
console.log(form);
alert("in submit handler");
}
According to the documents at jQuery validate
submitHandler (default: native form submit)
Type: Function()
Callback for handling the actual submit when the form is valid. Gets the form
as the only argument. Replaces the default submit. The right place to
submit a form via Ajax after it is validated.
Have also created a fiddle so that you can use it.

How to use the username availability checker script in form validation jquery

I am new to jquery. has i got the following code to check the username availability.
The script is working fine. to check the username avialble or not.
<script type="text/javascript" src="http://jqueryjs.googlecode.com/files/jquery-1.3.2.min.js"></script>
<script type="text/javascript">
$(function()
{
$('.user_name').keyup(function()
{
var checkname=$(this).val();
var availname=remove_whitespaces(checkname);
if(availname!=''){
$('.check').show();
$('.check').fadeIn(400).html('<img src="image/ajax-loading.gif" /> ');
var String = 'username='+ availname;
$.ajax({
type: "POST",
url: "available.php",
data: String,
cache: false,
success: function(result){
var result=remove_whitespaces(result);
if(result==''){
$('.check').html('<img src="image/accept.png" /> This Username Is Avaliable');
$(".check").removeClass("red");
$('.check').addClass("green");
$(".user_name").removeClass("yellow");
$(".user_name").addClass("white");
}else{
$('.check').html('<img src="image/error.png" /> This Username Is Already Taken');
$(".check").removeClass("green");
$('.check').addClass("red")
$(".user_name").removeClass("white");
$(".user_name").addClass("yellow");
}
}
});
}else{
$('.check').html('');
}
});
});
function remove_whitespaces(str){
var str=str.replace(/^\s+|\s+$/,'');
return str;
}
available.php contains following code.
if(isset($_POST['username']) && !empty($_POST['username'])){
$username=mysql_real_escape_string($_POST['username']);
$query="select * from sell where LOWER(uname)='$username'";
$res=mysql_query($query);
$count=mysql_num_rows($res);
if($count > 0){
echo "true";
}else{
echo "false";
}
}
Everything works fine. the ajax posting and checking the value exists or not.
But my problem is How i can include the above script in the following jquery validation script.
$(document).ready(function(){
$("#f2").validate({
debug: false,
rules: {
name: {
required:true,
minlength:3
//Here how to call the above script function..i stuck here..
}
});
});
Based on the name availability i need to process the form to submit.php other wise the form won't be submitted..
Any suggestions,Acceptable.
Add this script in validation function
<script>
$(document).ready(function(){
$("#f2").validate({
debug: false,
rules: {
name: {
required:true,
minlength:3,
remote:{
url: "available.php",
type: "post",
data: {
username: function() {
return $( ".user_name" ).val();
}
}
}
}
}
});
</script>
Remove "keyup" event function and than you are done...

How can I force jQuery Validate to check for duplicate username in database?

I'm coming into the middle of this project so I'm having to do a bit of re-writing because of sloppy code. I am using jQuery 1.6.1 and Validate 1.8.1.
First, here's the PHP which runs the back-end (dbquery.php):
include("../includes/dbconnection.php");
session_start();
$location='';
$action='';
if($_GET['action']=='')
$action=$_POST['action'];
else
$action=$_GET['action'];
if($action=='checkusername'){
$error='';
$username=$_GET['username'];
// exclude denied account
$checkuserquery=mysql_query("Select * from database_users as user LEFT OUTER JOIN database_approval as approval on user.user_id=approval.approval_user_id where (approval.approval_status IS NULL or approval.approval_status <> 4) and user_username='".$username."'");
$checkuserresult=mysql_numrows($checkuserquery);
if($checkuserresult>0) {
$error = 'false';
} else {
$error = 'true';
}
echo $error;
}
I'm trying to use jQuery Validate script to query the database for existing usernames on the fly. I either get two extremes: it never works or it always spits back given username as taken.
I believe the problem is that I cannot grab the input value of the username variable. When I create alert (username) within function (output), it returns nothing. My assumption is that .val() is only working when the page loads thus anything I'm typing into the input isn't working for some reason.
Here's the jQuery I've re-written and copied from sources online:
$(document).ready(function(){
$.validator.addMethod("checkAvailability",function(value,element){
var username = $("#username").val();
$.ajax({
url: "dbquery.php",
type: "GET",
async: false,
data: "action=checkusername&username="+username,
success: function(output) {
return output;
}
});
},"Sorry, this user name is not available");
// jQuery Validation script
$("#signup").validate( {
rules: {
username: {
required: true,
minlength: 5,
checkAvailability: true // remote check for duplicate username
},
},
messages: {
username: {
required: "Enter a username"
}
},
submitHandler: function(form) {
form.submit();
}
});
});
I am only a beginner with jQuery but am getting my hands pretty dirty with this code. Am I on the right track or should I use remote: under rules and username? I've been told that the remote method won't work because of the dynamnic nature of the input value I'm trying to validate.
The other major problem I've been running into is making the remote error message ONLY show up when a username already exists in the database. Unfortunately, it shows up whether dbquery.php comes back as true or false. If I try an existing username, it returns false, then I rewrite a new username that returns true, the message doesn't go away. Similarly, when I write a username and it returns true, I still get the remote error message.
The original coder was referencing getXMLHTTP and using ActiveXObject. The method he programmed seemed a little outdated so I'm trying to make the code a little more contemporary and clean it up.
5/25 - I am editing this to include the OLD original JavaScript code which works but is using the outdated method which I'd like to get away from (I have since removed the following code and replaced with jQuery above):
function getXMLHTTP() { //function to return the xml http object
var xmlhttp=false;
try{
xmlhttp=new XMLHttpRequest();
}
catch(e) {
try{
xmlhttp= new ActiveXObject("Microsoft.XMLHTTP");
}
catch(e){
try{
xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
}
catch(e1){
xmlhttp=false;
}
}
}
return xmlhttp;
}
//validate username
function validateUsername(username){
var strURL="dbquery.php?action=checkusername&username="+username;
var req = getXMLHTTP();
if (req) {
req.onreadystatechange = function() {
if (req.readyState == 4) {
// only if "OK"
if (req.status == 200) {
if(req.responseText=='notavailable'){
document.getElementById("errorusername").style.display="block";
document.getElementById("errorusername").innerHTML="<div id=\"errors\"><strong>"+username+"</strong> is already taken by another user.</div>";
error = true;
}
else{
error = false;
document.getElementById("errorusername").style.display="none";
}
} else {
alert("There was a problem while using XMLHTTP:\n" + req.statusText);
}
}
}
req.open("GET", strURL, true);
req.send(null);
}
}
Check when the validation function is getting called, what the value of username is and what the value of output is: is it true or "true"?
I'm guessing latter: a string, so you could just do:
return output === "true" ? true : false; // I sincerely recommend using === here
Since if you return "false"; will evaluate to true because it's a non-empty string - yay dynamic langauges! :/
Example with remote:
$("#signup").validate( {
rules: {
username: {
required: true,
minlength: 5,
remote: {
url: "dbquery.php",
type: "get",
data: {
action: function () {
return "checkusername";
},
username: function() {
var username = $("#username").val();
return username;
}
}
}
}
},
messages: {
username: {
required: "Enter a username"
}
},
submitHandler: function(form) {
form.submit();
}
});
To set a custom error message your PHP file must return the message instead of false, so echo "Sorry, this user name is not available" in your PHP file.
While you adding addMethod you should return true or false from server side.
and also that value have to be returned from addMethod.
ie something like this
$.validator.addMethod("checkAvailability",function(value,element){
var parameter="action=checkusername&username="+username;
$.ajax({
url: "dbquery.php",
type: "POST",
async: false,
data: parameter
success:function(output)
{
return output
}
});
},"Sorry, this user name is not available");
I faced the same problem, But I find the easiest solution just return true or false after encoding into json through php.
if ($users->username_exists())
{
echo json_encode(FALSE);
}else{
echo json_encode(TRUE);
}
On your server side script, try returning true or false instead of available and notavailable, as both of those strings are equivalent to true.
My code:
$( "#myform" ).validate({
rules: {
EMAIL: {
remote: {
type: "post",
url: "checkMail.php",
data:{checkUsername:function(){return $("#EMAIL").val()}
}
}
}
},messages:{EMAIL:{remote: "Already taken!"}}
});

Categories

Resources