how to use jquery ajax validation using remote? - javascript

I have written a program in jsp to check whether an email address exist in database or not , if it exist it will give me "1" and if it does not exist it will give me default as "0" , which is working perfectly
Now i want to call this url in my jquery and validate my email address , i have written some code in jquery but it is not working , my error message for email is working but for remote is not working. Please need some help
$(document).ready(function () {
$("#user_form").validate({
rules: {
phone: {
required: "true",
minlength: "10"
},
email: {
required: "true",
email: "true",
remote: {
url: 'validate_emailid_succes.jsp',
type: "POST",
data: {
email: function () {
return $("#email").val()
}
}
}
}
},
messages: {
email: {
required: "Please enter your email address",
email: "Please enter a valid email address",
remote: jQuery.validator.format("Email ID is already taken")
},
phone: "Please enter a 10 digit mobile number"
}
});
});
Need some guidance so that i can understand where i am going wrong.
Thank You

Related

Pass variables to URL in ajax

I have the below ajax call in which I am trying to post the registration data directly to URL, but is there anyway I can store those variables and then pass it into the URL. Please help thank you in advance.
You can see the Script.js in this plunker
jquery:
$(function() {
/* Registration form for the website */
/* validation */
$("#register-form").validate({
rules: {
firstName: {
required: true
},
lastName: {
required: true
},
userName: {
required: true,
minlength: 4
},
email: {
required: true,
email: true
},
password: {
required: true,
minlength: 8,
maxlength: 15
},
cpassword: {
required: true,
equalTo: '#password'
},
},
messages: {
userName: "please enter a valid user name",
password: {
required: "please provide a password",
minlength: "password at least have 8 characters"
},
email: "please enter a valid email address",
cpassword: {
required: "please retype your password",
equalTo: "password doesn't match !"
}
},
submitHandler: submitForm
});
/* validation */
/* form submit */
function submitForm() {
var data = $("#register-form").serialize();
// var data={
// firstName: $('#firstName').val(),
// }
$.ajax({
url: 'http://localhost:8000?userName=&password=&firstName=&lastName=&email=',
type: 'POST',
data: data,
beforeSend: function() {
$("#error").fadeOut();
$("#btn-submit").html('<span class="glyphicon glyphicon-transfer"></span> sending ...');
},
success: function(data) {
if (data === 0) {
$("#error").fadeIn(1000, function() {
$("#error").html('<div class="alert alert-danger"> <span class="glyphicon glyphicon-info-sign"></span> Sorry email already taken !</div>');
$("#btn-submit").html('<span class="glyphicon glyphicon-log-in"></span> Create Account');
});
} else if (data == 1) {
$("#btn-submit").html('<img src="btn-ajax-loader.gif" /> Signing Up ...');
} else {
$("#error").fadeIn(1000, function() {
$("#error").html('<div class="alert alert-danger"><span class="glyphicon glyphicon-info-sign"></span> ' + data + ' !</div>');
$("#btn-submit").html('<span class="glyphicon glyphicon-log-in"></span> Create Account');
});
}
}
});
return false;
}
});
url: 'http://localhost:8000?userName=&password=&firstName=&lastName=&email=',
type: 'POST',
data: data,
become
url: 'http://localhost:8000?' + data,
type: 'GET',
//data: data,
Your AJAX URL is wrong, you do not need to type in the full address. The Serialize method should do that for you. All you need is localhost:8000? + data. And as #zer00ne said, never use a GET if your sending in a password, it will show up on the URL. As a rule of thumb, anything sent in a form should be a POST request, unless some rare cases which I am not aware of.
My suggestion:
$.ajax({
url: 'http://localhost:8000?',
type: 'POST',
data: data,
This way your sending in your information to the proper place and securely.

How does return false work inside validate plugin submitHandler

I was just going through the validator plgin examples and found a snippet of code online:
$('#testimonials-form').validate({
rules: {
"t-title": {
required: true,
minlength: 5
},
"t-text": {
required: true,
minlength: 15
},
"person-name": {
required: true,
minlength: 4
},
"photo": {
required: true,
accept: 'image/*'
}
},
messages: {
"t-title": {
required: "A title is needed",
minlength: "minimum 4 characters"
},
"t-text": {
required: "A testimonial is needed",
minlength: "minimum 15 characters"
},
"person-name": {
required: "A name is needed",
minlength: "minimum 4 characters"
},
"photo": {
required: "An image for the testimonial giver is needed",
accept: "Only image file type is accpeted , please check that the file you tried to upload was an image"
}
},
submitHandler: function (form) {
var formData = new FormData();
formData.append('photo', $('input[type=file]')[0].files[0]);
formData.append('t-title', $('input[name=t-title]').val());
formData.append('t-text', $('textarea[name=t-text]').val());
formData.append('person-name', $('input[name=person-name]').val());
$.ajax({
type: 'POST', // define the type of HTTP verb we want to use (POST for our form)
url: 'inc/database.php', // the url where we want to POST
data: formData,
// THIS MUST BE DONE FOR FILE UPLOADING
contentType: false,
processData: false,
// ... Other options like success and etc
});
return false;
}
});
Now how come the return false works here , in spite of not being attached to a submit button ? I used the above code and it worked perfectly fine , i was just curious to know how the above code works and how especially the return false works ?
EDIT :: i know how return false works , i am asking how come it work's here when they are not attached to the submit button.
Thank you.
The submit handler is called when a submit event on the form is registered. It doesn't have to be tied to a button, just the event.

Error: jQuery jquery.min.js?_=1420285687057:4 Uncaught TypeError: undefined is not a function

I have problem with jquery validate plugn and history API, when i click few times
i have error jquery.min.js?_=1420288991396:4 Uncaught TypeError: undefined is not a function, when I comment a fragment with validate, script works fine. How concat this script.
In file script.js i have:
$(document).ready(function(){
$("#loginForm").validate({
rules: {
username: {
required: true,
minlength: 2
},
password: {
required: true,
minlength: 5
},
},
messages: {
username: {
required: "Please enter a username",
minlength: "Your username must consist of at least 2 characters"
},
password: {
required: "Please provide a password",
minlength: "Your password must be at least 5 characters long"
},
},
submitHandler: function() {
var username=$("#usernameLogin").val();
var password=$("#passwordLogin").val();
var dataString = 'username='+username+'&password='+password+'&tag=login';
if($.trim(username).length>0 && $.trim(password).length>0){
$.ajax({
type: "POST",
url: "include/help4meApi.php",
data: dataString,
cache: false,
success: function(data){
if(data){
if($("#rememberMe:checked").val()){
checkCookie(username);
}
window.location.href = "index.php";
}
else{
$("#error").html("<label class='error'>Wrong password or username!</label>");
console.log("Wrong password or username!");
}
}
});
}
return false;
}
});
// validate signup form on keyup and submit
$("#signupForm").validate({
rules: {
firstname: {
required: true,
minlength: 3
},
lastname: "required",
username: {
required: true,
minlength: 2
},
password: {
required: true,
minlength: 5
},
confirm_password: {
required: true,
minlength: 5,
equalTo: "#password"
},
email: {
required: true,
email: true
}
},
messages: {
firstname: {
required: "Please enter your firstname",
minlength: "Your firstname must consist of at least 3 characters"
},
lastname: "Please enter your lastname",
username: {
required: "Please enter a username",
minlength: "Your username must consist of at least 2 characters"
},
password: {
required: "Please provide a password",
minlength: "Your password must be at least 5 characters long"
},
confirm_password: {
required: "Please provide a password",
minlength: "Your password must be at least 5 characters long",
equalTo: "Please enter the same password as above"
},
email: "Please enter a valid email address",
},
submitHandler: function() {
var username=$("#username").val();
var password=$("#password").val();
var firstname=$("#firstname").val();
var lastname=$("#lastname").val();
var email=$("#email").val();
var dataString = 'username='+username+'&password='+password+'&firstname='+firstname+'&lastname='+lastname+'&email='+email+'&tag=register';
if($.trim(username).length>0 && $.trim(password).length>0){
$.ajax({
type: "POST",
url: "include/help4meApi.php",
data: dataString,
cache: false,
success: function(data){
if(data){
console.log(data);
$(".register_notification").html("<label class='error' style='background:#6DC066'>Register successfully!</label>");
}
else{
$(".register_notification").html("<label class='error'>Username already exists, please choose another one!</label>");
}
}
});
}
return false;
}
});
// propose username by combining first- and lastname
$("#username").focus(function() {
var firstname = $("#firstname").val();
var lastname = $("#lastname").val();
if (firstname && lastname && !this.value) {
this.value = firstname + "." + lastname;
}
});
$("footer a").click(function(e){
//e.preventDefault();
/*
if uncomment the above line, html5 nonsupported browers won't change the url but will display the ajax content;
if commented, html5 nonsupported browers will reload the page to the specified link.
*/
//get the link location that was clicked
pageurl = $(this).attr('href');
//to get the ajax content and display in div with id 'content'
$.ajax({url:pageurl,success: function(data){
$('#login_box').html(data);
}});
//to change the browser URL to 'pageurl'
if(pageurl!=window.location){
window.history.pushState({path:pageurl},'',pageurl);
}
return false;
});
});
$(window).bind('popstate', function() {
if(!location.pathname.localeCompare('/login.php')){
$.ajax({url:location.pathname,success: function(data){
$('body').html(data);
}});
}
else{
$.ajax({url:location.pathname,success: function(data){
$('#login_box').html(data);
}});
}
});
From jQuery library:
// Get transport
transport = inspectPrefiltersOrTransports( transports, s, options, jqXHR );
// If no transport, we auto-abort
if ( !transport ) {
done( -1, "No Transport" );
} else {
jqXHR.readyState = 1;
// Send global event
if ( fireGlobals ) {
globalEventContext.trigger( "ajaxSend", [ jqXHR, s ] );
}
// Timeout
if ( s.async && s.timeout > 0 ) {
timeoutTimer = setTimeout(function() {
jqXHR.abort("timeout");
}, s.timeout );
}
try {
state = 1;
transport.send( requestHeaders, done );
} catch ( e ) {
// Propagate exception as error if not done
if ( state < 2 ) {
done( -1, e );
// Simply rethrow otherwise
} else {
throw e;
}
}
}
it shows throw e.
I can't think of any reason why using the browser's "back" button would cause the JavaScript to fail. Everything should be cached and continue to work as before.
The error you're getting is similar to the error you'd get if you failed to include the plugin.
Here is how you're including the jQuery Validate plugin...
<script src="http://jqueryvalidation.org/files/dist/jquery.validate.js"></script>
Notice how you're hotlinking to the plugin hosted on the developer's own domain. (likely for his demos and/or to download.) This error might be caused by a timing issue, the plugin not loading fast enough from this URL.
The developer has provided his plugin on two different free CDN services where "hotlinking welcome". So instead of leaching the plugin directly from his domain, try hotlinking to the CDN links provided here.
<script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.13.1/jquery.validate.js"></script>

Jquery form not submitting or validating

I have the following form validation and submission script in jquery but for some reason its not working. It looks like its submitting but when i click submit it just resets the form and it doesn't validato or do the ajax post. Does anyone know what i am doing wrong here?
MODIFIED CODE
<script type="text/javascript">
$(function(){
$('#form').submit(function(e){
e.preventDefault();
$("#form").validate({debug: false,
rules: {
name: "required",
email: {
required: true,
email: true
},
phone: {
required: true,
phone: true
}
},
messages: {
name: "Please let us know who you are.",
email: "A valid email will help us get in touch with you.",
phone: "Please provide a valid phone number.",
},
submitHandler: function() {
// Send the request
$.post('/submit.php', {
name: $('#name').val(),
email: $('#email').val(),
phone: $('#phone').val(),
message: $('#message').val()
}, function(d){
alert("Thank you for submitting your request someone will contact your shortly.");
});
}
});
});
});
</script>
You just need to add
$('#form').submit(function(e) {
....
return false;
});
to the end of the submit, this will avoid executing the actual submit of the form.
UPDATE:
As pointed out by Dustin, preventDefault might be better if you don't want to stop your event from bubbling up..
$('#form').submit(function(e) {
....
e.preventDefault();
});
I switched your code a bit, seems you using jquery validate?, their documents have the correct way to submit a form. http://jqueryvalidation.org/documentation/#too-much-recursion
<script type="text/javascript">
$("#form").validate({
debug: false,
rules: {
name: "required",
email: {
required: true,
email: true
},
phone: {
required: true,
phone: true
}
},
messages: {
name: "Please let us know who you are.",
email: "A valid email will help us get in touch with you.",
phone: "Please provide a valid phone number.",
},
submitHandler: function(form) {
// Stop the form actually posting
e.preventDefault();
// Send the request
$.post('/submit.php', {
name: $('#name').val(),
email: $('#email').val(),
phone: $('#phone').val(),
message: $('#message').val()
}, function(d){
alert("Thank you for submitting your request someone will contact your shortly.");
});
}
});

jQuery Validator Plugin - check for existing Username/Email in mysql database

I've successfully created a form that submits and adds users to a mysql database, and form validation with 'jQuery Validator' plugin works great for everything except checking to see if the username already exists in the database...
I've just spent about 8 hours reading and trying to figure out a way to define a new method with the 'jQuery Validator' plugin. I just can't seem to understand how I would go about checking the database for the entered username or email and return whether it already exists or not using jQuery.
My code:
<script src="../assets/js/main.js"></script>
<script src="../assets/js/ajax.js"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.11.0/jquery.validate.min.js"></script>
<!-- FORM VALIDATION -->
<script type="text/javascript">
jQuery.validator.addMethod("checkExists",
function(value, element) {
//No idea what to call here
},
"Username already exists."
);
//<![CDATA[
$(window).load(function(){
$("form").validate({
rules: {
username: {minlength: 3, required: true, checkExists: true},
email: {email: true, required: true},
pass1: {minlength: 3, required: true},
pass2: {minlength: 3, required: true, equalTo: "#pass1"},
country: {required: true},
tandc: {required: true},
},
messages: {
username: {required: "You need to enter a Username."},
email: {required: "You need to enter an Email Address."},
pass1: {required: "You need to enter a Password."},
pass2: {required: "You need to enter your password again.", equalTo: "Your passwords don't match."},
country: {required: "You need to tell us where you live."},
tandc: {required: "You need to read and agree to the Terms and Conditions to use CGE."}
},
showErrors: function(errorMap, errorList) {
$.each(this.successList, function(index, value) {
return $(value).popover("hide");
});
return $.each(errorList, function(index, value) {
var _popover;
console.log(value.message);
_popover = $(value.element).popover({
trigger: "manual",
placement: "right",
content: value.message,
template: "<div class=\"popover\"><div class=\"arrow\"></div><div class=\"popover-inner\"><div class=\"popover-content\"><p></p></div></div></div>"
});
_popover.data("popover").options.content = value.message;
return $(value.element).popover("show");
});
}
});
});//]]>
</script>
If anyone clever could please amend my code to show me how I should have done it, it would be a great help - I feel like I'm about to go crazy!
Thanks in advance, can't wait to see the solution :-)
EDIT - This is my current code
Nothing seems to happen at all, I feel like I'm closer though:
CURRENT CODE:
signup.php
$(window).load(function(){
$("form").validate({
rules: {
username: {minlength: 3, required: true},
email: {email: true, required: true, remote: {url: "./validation/checkUnameEmail.php", type : "post"}},
pass1: {minlength: 3, required: true},
pass2: {minlength: 3, required: true, equalTo: "#pass1"},
country: {required: true},
tandc: {required: true}
},
checkUnameEmail.php
<?php
include_once(".../php_includes/db_conx.php");
$email = urldecode($_POST['email']);
$result = mysqli_query($db_conx, "SELECT * FROM users WHERE email = '$email' LIMIT 1;");
$num = mysqli_num_rows($result);
if($num == 0){
echo "true";
} else {
echo "E-Mail-Adresse schon registriert.";
}
mysqli_close($db_conx);
?>
*db_conx.php*
<?php
$db_conx = mysqli_connect("localhost", "root", "root", "membership");
//Evlauate the connection
if (mysqli_connect_errno()){
echo mysqli_connect_error();
exit();
}
?>
$.validator.addMethod("checkExists", function(value, element)
{
var inputElem = $('#register-form :input[name="email"]'),
data = { "emails" : inputElem.val() },
eReport = ''; //error report
$.ajax(
{
type: "POST",
url: validateEmail.php,
dataType: "json",
data: data,
success: function(returnData)
{
if (returnData!== 'true')
{
return '<p>This email address is already registered.</p>';
}
else
{
return true;
}
},
error: function(xhr, textStatus, errorThrown)
{
alert('ajax loading error... ... '+url + query);
return false;
}
});
}, '');
OR
You can use the remote method instead which allows you to do remote checks: http://docs.jquery.com/Plugins/Validation/Methods/remote
Eg.
$("#yourFormId").validate({
rules: {
email: {
required: true,
email: true,
remote: {
url: "checkUnameEmail.php",
type: "post"
}
}
},
messages: {
email: {
required: "Please Enter Email!",
email: "This is not a valid email!",
remote: "Email already in use!"
}
}
});
checkUnameEmail.php //Eg.
<?php
$registeredEmail = array('jenson1#jenson.in', 'jenson2#jenson.in', 'jenson3#jenson.in', 'jenson4#jenson.in', 'jenson5#jenson.in');
$requestedEmail = $_REQUEST['email'];
if( in_array($requestedEmail, $registeredEmail) ){
echo 'false';
}
else{
echo 'true';
}
?>
js code
username: {
required: true,
minlength: 5,
remote: '/userExists'
},
Php code to check if exist and return messages
public function userExists()
{
$user = User::all()->lists('username');
if (in_array(Input::get('username'), $user)) {
return Response::json(Input::get('username').' is already taken');
} else {
return Response::json(Input::get('username').' Username is available');
}
}
For WordPress & PHP
Most important thing is instead or return true or false, need to echo 'true' or 'false'
jQuery or JS
email: {
required: true,
minlength: 6,
email: true,
remote:{
url : 'your ajax url',
data: {
'action': 'is_user_exist',
},
},
},
WordPress or PHP Backend Code
In backend you will automatically get the value of field via GET method.
/*
*# Check user exists or not
*/
if( !function_exists('is_user_exists_ajax_function') ):
function is_user_exists_ajax_function() {
$email = $_GET['email'];
if( empty($email) && is_email($email) ):
wp_send_json_error( new \WP_Error( 'Bad Request' ) );
endif;
$is_email = email_exists( $email );
if($is_email):
echo 'false';
else:
echo 'true';
endif;
wp_die();
}
add_action( 'wp_ajax_is_user_exist', 'is_user_exists_ajax_function' );
add_action( 'wp_ajax_nopriv_is_user_exist', 'is_user_exists_ajax_function' );
endif;

Categories

Resources