jquery validation plugin and check unique field? - php

I am currently using jQuery validation plugin with cakephp in my new project.
It's working perfectly untill I need to make unique check to email field through ajax to check with the database..
I didn't know how to make the plugin make a unique validation to email from db.
thanx

I reckon you are refering to using an AJAX call (via the plugin) to check for unique email with the server, yea?
I would suggest using the addMethod of the validation plugin to create a custom validation in which you can make an AJAX call (which will be part of the jQuery core).
There's an SO post on this topic which you can explore:
JQuery Validate Plugin - How to create a simple, custom rule?
Do note that you will have to implement the server-side script yourself.
Here's another article which should be useful (using jQuery and PHP):
Check email already exist – Ajax – Jquery

The syntax is simple
$.validator.addMethod("eventName",
function(value, element) {
// condition returns true or false
}, "Error message to display");
});
Event name is called in the form
<input type="text" name="name" class="eventName" />
Refer this link if any more doubts
jQuery Validate Plugin - How to create a simple custom rule?

If you want to check if the email is unique you can use remote rule.
It is from: http://jqueryvalidation.org/remote-method
Example: Makes the email field required, an email and does a remote request to check if the given address is already taken.
$( "#myform" ).validate({
rules: {
email: {
required: true,
email: true,
remote: "check-email.php"
}
}
});
Example: Makes the email field required, an email and does a remote request to check if the given address is already taken. In addition, the http method is set to “post” and the username is sent alongside the email address.
$( "#myform" ).validate({
rules: {
email: {
required: true,
email: true,
remote: {
url: "check-email.php",
type: "post",
data: {
username: function() {
return $( "#username" ).val();
}
}
}
}
}
});

Try something like
$.validator.addMethod("unique",
function(value, element, params) {
var isUnique = false;
if(value == '')
return isUnique;
id_send= '';
if(params[1] !='')
id_send ='id='+params[1]+'&';
$.ajax({
url: "path"+params[2],
type : 'GET',
async: false,
data: id_send+'field=' + params[0] + "&value=" + value,
dataType: 'json',
cache: true,
success: function(data){
isUnique = data;
}
});
return isUnique;
},
jQuery.validator.format("Value already in use")
);
In the above code:
path is the root path of your application;
params[0] is the name of attribute to check unique;
params[1] is the id of the object, if you want to check in edit too, so exclude himself;
params[2] is the path to the php file that gonna check.
Resulting in something like:
rules:
{
email: {
required: true,
unique:['email', $('#user_id').val(),'uniqueemail.php'],
email: true
},
The PHP uniqueemail.php, search for the value in field email, if return empty or the user with id equals $('#user_id').val() so return true, else return false.
Note that the async attribute is set false, this is a set back but is gonna do the job.

Related

Jquery validation for duplicate email using laravel

Hi I am using laravel code to check the email is unique or not and at the front end i am using jquery as follows:
blade.php page
user_email: {
required: true,
email: true,
remote: {
url: base_url + "/validate_email",
type: "post"
}
},
and on post i used the following method validation_email in controller:
function validate_email(Request $request) {
if ($request->input('user_email') !== '') {
if ($request->input('user_email')) {
$rule = array('user_email' => 'Required|email|unique:users');
$validator = Validator::make($request->all(), $rule);
}
if (!$validator->fails()) {
die('true');
}
}
die('false');
}
But when I fill the email and it validate it shows an error as CsrftokenMismatch Exception. When i disable the csrf token then csrf token then code is working otherwise it throws an exception.
Please suggest me some solution for this.. Thank You
Pass the token along in your Request in your blade.
remote: {
url: base_url + "/validate_email",
type: "post"
data: {
_token: function() {
return "{{csrf_token()}}"
}
}
}
its easy you CSRF token is in a hide field in your form, i dont remember de id but you can get that value and send it with the email in your post request for example:
required: true,
email: true,
remote: {
url: base_url + "/validate_email",
**YOU CAN ADD THE PARAMS HERE ( _id=" +$("#_id").val() +"),**
type: "post"
}
bassically you have add the token who is in your form to your post request, that value is hidden in the form, i hope i explain myself well

Prevent Email Spam after using reCaptcha

All,
I've got a form on my page that I use to send emails. On the form page I have the following code:
<input type="text" name="Name" id="your_name" class="contact_form_input_text">
<input type="text" name="Email_Address" id="your_email" class="contact_form_input_text">
<input type="text" name="fill_me_out" id="fill_me_out">
<input type="button" value="Send" id="submit_contact_form_button">
The first text box is a lamecaptcha and I check it on the PHP side to make sure that it wasn't filled out. I also hide it using some JS with this:
jQuery(function(){
jQuery("#fill_me_out").hide();
});
I then have the following form validation before my page submits using jQuery validator:
jQuery("#contact_form").validate({
rules: {
Email_Address: {
required: true,
email: true
},
Name: {
required: true
}
},
messages: {
Email_Address: {
required: "Please enter an email address!",
email: "Please enter a valid email address!"
},
Name: {
required: "Please enter your Name!"
}
}
});
jQuery("#submit_contact_form_button").click(function(event) {
if (jQuery("#contact_form").valid()) {
challengeField = jQuery("input#recaptcha_challenge_field").val();
responseField = jQuery("input#recaptcha_response_field").val();
var html = jQuery.ajax({
type: "POST",
url: site_url + "ajax.recaptcha.php",
data: "recaptcha_challenge_field=" + challengeField + "&recaptcha_response_field=" + responseField,
async: false
}).responseText;
if(html == "success")
{
//$("#captchaStatus").html(" ");
// Uncomment the following line in your application
//return true;
jQuery("#contact_form").submit();
}else{
jQuery("#captchaStatus").html("Your captcha is incorrect. Please try again");
Recaptcha.reload();
return false;
}
}
return false;
});
If everything is filled out correctly the page then submits. I have the following check to check the lame captcha:
$lamecaptcha_check = $_POST['fill_me_out'];
if($lamecaptcha_check!=""){
echo '[box style="alert"]Why are you trying to spam us? It could be because you don\'t have Javascript enabled and filled out an incorrect box![/box]';
}else{
//Send the form using mail
}
To submit the form is a button and not a submit so it has to go through the jquery validation to do even be submitted. Somehow I'm still getting blank email messages to come through. Does anyone know anything else I can possibly do to prevent spam/blank email messages? I was thinking I should check the variables on the back end to make sure they are not blank but the form shouldn't even be submitted unless there are some values so I require a valid email address on the initial page. Any ideas are appreciated!
Thanks!
Just because you have a submit button go through jQuery to work, doesn't mean the form can't be submitted otherwise.
A spambot would probably examine the HTML of your form, look at the different fields, and then just send a POST request with the relevant information. It will not evaluate your jQuery.
If you want to do something like this, set the form's action="javascript:;", then update it in your jQuery to the actual value right before submitting.

Using returned data to perform additional javascript tests with ajax

I have a mail.php file that gets called by an ajax script. For completeness, the ajax script is attached below. All the mail.php file does is perform some server-side validation, and if everything passes, sends an email with mail() and the data sent from the ajax request.
What I want to do is perform some additional javascript actions based on the response of the request. You can see that at its current state, the response of the request is simply echo'd to the screen, which is fine. But now I want to modify HTML elements based on the response.
For example, say I want to append an image called "OK" to the page if the mail was sent, and else append an image called "FALSE" to the page if the mail was not sent. What I'd like to do (in pseudocode) is this:
if ( request is OKAY ) $('.contact').append('<img src"OK"');
else ( $('.contact').append('<img src="BAD'');
Is there any way to perform this?
Thanks!
The ajax script is shown below:
$('.submit').click(function() {
$('div.load').html('<img src="images/load.gif" alt="Loading..." id="loading" />');
//creation of variables to send
var name = $('#name').val();
email = $('#email').val();
phone = $('#phone').val();
$.ajax({
url: 'mail.php',
type: 'POST',
data: 'name=' + name + '&email=' + email + '&phone=' + phone,
success: function(result) {
$('p.error,p.correct').remove();
$('.contact').append(result);
$('#loading').fadeOut(500, function() {
$(this).remove();
});
}
});
return false;
});
Assuming your PHP responds with the text "OKAY":
if (result==="OKAY")
$('.contact').append('<img src"OK" />');
else
$('.contact').append('<img src="BAD" />');
Or:
$('.contact').append('<img src"' + (result==="OKAY"?'OK':'BAD') + '" />');
An alternative is to update your PHP so that it returns html that includes both a message and the image, e.g., on success it could return:
Your request was successful. <img src="OK" />
"I should mention that I'd like to keep the current response there as well to make sure that non-JS users also get the appropriate message"
Non-JS users will not be getting anything because your Ajax code uses JS...
You'll probably want the server-side handler to return its status via the response, e.g. formatted as JSON (PHP has a function for that).
To achieve that and still get a good response for non-JavaScript users, too, I suggest using a different URL in the AJAX than in your form's action attribute, e.g. with an extra query parameter à la ?json=1. Then your script can normally do its standard output and return easily parseable JSON (e.g. an associative array containing both the current response text and a status code) if the parameter is present. jQuery's AJAX interface can automatically parse the response as JSON if you tell it to.
That's the purpose of the success / error objects in the initialization of the AJAX call. You'll want to add three failure cases. The first two failure cases will come through the success ajax call, both due to server side issues. The second error case will be in the errorcase of the ajax call. Also, your web service should return a success parameter. Alter your code to something like this to achieve what you've described:
$('.submit').click(function() {
$('div.load').html('<img src="images/load.gif" alt="Loading..." id="loading" />');
//creation of variables to send
var name = $('#name').val();
email = $('#email').val();
phone = $('#phone').val();
$.ajax({
url: 'mail.php',
type: 'POST',
data: 'name=' + name + '&email=' + email + '&phone=' + phone,
success: function(result) {
if (result) {
if (result.success) {
$(".contact").append("<img src='OK.jpg'>");
$('p.error,p.correct').remove();
$('.contact').append(result);
$('#loading').fadeOut(500, function() {
$(this).remove();
});
} else { // The server returned data, but there was an error on the server side.
$(".contact").append("<img src='BAD.jpg'>");
}
} else { // The server had a problem and didn't return any data.
$(".contact").append("<img src='BAD.jpg'>");
}
}
error: function(XMLHttpRequest, textStatus, errorThrown) {
// There was an error in the AJAX call.
$(".contact").append("<img src='BAD.jpg'>");
},
}
});
return false;
});
Also, you're using the data parameter wrong. Ignore the data section of the above example and use this as your data:
data: {
name: name,
email: email,
phone: phone
}
This looks strange to people who don't understand JavaScript objects. Let me know if you would like me to explain why we define the variables with the same names, e.g.: name: name.

How to make jQuery Validator remotely trigger errorPlacement?

Can anyone please tell me how I can get the jQuery Validator to call the errorPlacement handler when a remote function fails? I have provided a short example:
Cliff Notes: According to their documents, I have to output JSON, but I must have missed something because do I just echo out json_encode, or do I provide a key like echo json_encode(array('result' => 0)) as it says in this block of text.
JS:
var validator = $("form#signup").validate({
onfocousout: true,
rules: {
email: {
required: true,
email: true,
remote: {
type: "POST",
url: 'test.php',
data: {
email: function() {return $("#email").val();}
}
}
},
errorPlacement: function(error, el) {
console.log('ERR' + $(el).attr('id'));
}
}
});
PHP:
<?php
echo false; // This should allow the errorPlacement to call shouldn't it?
I think you need to echo false as a string from your PHP script:
<?php
echo 'false';
I've created a jsfiddle based on your question. The pastebin link just returns the word "false".

jQuery to database - registration form with validation

I find this tutorial in 9lessons.com : http://www.9lessons.info/2011/01/gravity-registration-form-with-jquery.html
It's about a registration form with validation.
I want to send data to DB.
// Submit button action
$('#submit').click(function()
{
var email=$("#email").val();
var username=$("#username").val();
var password=$("#password").val();
if(ck_email.test(email) && ck_username.test(username) && ck_password.test(password) )
{
$("#form").show().html("<h1>Thank you!</h1>");
///// if OK
///// Show thanks
//// else
//// Error, try again
}
return false;
});
How can I do ?? I searched in internet in jQuery tutorial and I find much codes ...
This tutorial will walk you the entire process:
http://net.tutsplus.com/tutorials/javascript-ajax/submit-a-form-without-page-refresh-using-jquery/
It implements jQuery.post and calls a PHP script that will allow you to process the data.
You will need to use Ajax to submit the data to a backend script (such as PHP) to do the actual database interaction. I'd recommend using POST:
http://api.jquery.com/jQuery.post/
you can use jquery post method
$.post("test.php", $("#testform").serialize());
or for more detail visit this link
jquery form post method
Finally I inserted data form to database... I have a problem.. I forgot to verify if email is available or not !
I added this lines from an other tutorial in email verification to test if email exist in DB or not.
First I send email to check_availability.php
if mail exist an error message appear else, the password fiel must appear ...
Like you see in picture, I verify the existence of an email adress and availibality and unavailability message appear but not correctly ...
$('#email').keyup(function()
{
var email=$(this).val();
if (!ck_email.test(email))
{
$(this).next().show().html("Enter valid email");
}
else
{
//$(this).next().hide();
//$("li").next("li.password").slideDown({duration: 'slow',easing: 'easeOutElastic'});
$.ajax
({
type: "POST",
url: "user_availability.php",
data: "email="+ email,
success: function(msg)
{
$("#status").ajaxComplete(function(event, request, settings)
{
if(msg == 'OK')
{
/*$("#email").removeClass('object_error'); // if necessary
$("#email").addClass("object_ok");
$(this).html(' <img align="absmiddle" src="accepted.png" /> ');*/
//////////////////
$(this).next().hide();
$("li").next("li.password").slideDown({duration: 'slow',easing: 'easeOutElastic'});
//////////////
}
else
{
$("#email").removeClass('object_ok'); // if necessary
$("#email").addClass("object_error");
$(this).html(msg);
}
});
}
});
}
});
The tow first comment lines are the default ines used to show the next field //$("li").next("li.password").slid ...
Like you see I add them in Ok test section ....

Categories