How to make jQuery Validator remotely trigger errorPlacement? - php

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".

Related

check username exists using ajax

I use this code to check username exists in database before or not. code works good and shows available or taken username. now i want to submit button should be disable when user select username that was taken befor and enable when username available . please guide me how.
$(document).ready(function() {
$('#username').keyup(function() {
$.post('adm/chk_uname_avail.php', {
uname : changeuser.username.value
}, function(result){
$('#available').html(result);
})
})
})
I'm using the old $.ajax function and make sure you have a data keyed taken (as example) with boolean type on adm/chk_uname_avail.php and notice that you should return JSON data type from it.
Example of adm/chk_uname_avail.php
<?php
//return response as JSON
header('Content-type:application/json;charset=utf-8');
....
....
....
$data['taken'] = true; //show this response to ajax
echo json_encode($data);
?>
Ajax
$(document).ready(function() {
$('#username').on('keyup', function() {
$.ajax({
type: 'POST',
url: 'adm/chk_uname_avail.php',
data: {uname : changeuser.username.value},
success: function(result) {
var $btn = $('#submiButton');
if (result.taken) {
$btn.prop('disabled', true);
} else {
$btn.prop('disabled', false);
}
//As #Mikey notice, You can just use this as simply as
//$('#submiButton').prop('disabled', result.taken);
}
});
});
});
Use .attr() method of jQuery to make the submit disabled on certain condition.
So you can update your jQuery like this,
$.post('adm/chk_uname_avail.php', {
uname : changeuser.username.value
}, function(result){
$('#available').html(result);
if(/* CHECK FOR CERTAIN CONDITION */) {
$('#submit_btn').attr('disabled','disabled');
}
});
To remove the disabled attribute you can use removeAttr() method of jQuery. Like this,
$('#submit_btn').removeAttr('disabled');
http://api.jquery.com/attr/
https://api.jquery.com/removeAttr/

select2 values from php

I really stuck with select2 and the tags mode. I want to let the user enter data as tags. Seperated by " " and ",". No problem. I've got this.
Now I want to gather the already available tags by a php file. I've already tried several snippets from google and here. The php file returns a json_encode. Does anybody see what I am doing wrong?
Here is the code:
if($('#s2_tag_handler_receipient').length) {
$('#s2_tag_handler_receipient').select2({
tags: true,
tokenSeparators: [",", " "],
createSearchChoice: function (term, data) {
if ($(data).filter(function () {
return this.text.localeCompare(term) === 0;
}).length === 0) {
return {
id: term,
text: term
};
}
},
multiple: true,
ajax: {
url: "imapMailBox/autoCompleteReceipientsJson.php",
dataType: "json",
data: function (term, page) {
return {
q: term
};
},
results: function (data, page) {
return {
results: data
};
}
}
});
}
This is the php file:
<?php
$return[]=array('Paul','NotPaul');
echo json_encode($return);
?>
Try with :
<?php
$return=array('Paul','NotPaul');
echo json_encode($return);
?>
This will give : ["Paul","NotPaul"]
In your version it gave : [["Paul","NotPaul"]]

php jquery remote validate problem

<script type="text/javascript">
$().ready(function() {
jQuery.validator.addMethod("captcha", function(value, element) {
$.ajax({ url: "verifyCap.php",
type: "GET",
data: "txtCaptcha="+value,
success:
function(msg) {
if(msg == "true")
return true; // already exists
return false;
}
});
},"");
// validate signup form on keyup and submit
$("#signupForm").validate({
rules: {
title: "required",
contactname: "required",
email: {
required: true,
email: true
},
comment: "required",
txtCaptcha:{
required: true,
captcha: true
}
},
messages: {
contactname: "Please enter your contact name",
email: "Please enter a valid email address",
comment: "Please enter your system requierment",
txtCaptcha: {
required:"Please enter verification code",
captcha: "The verification code is incorrect"
}
}
});
});
My verifyCap.php
<?php
session_start ();
if ($_SERVER ["REQUEST_METHOD"] != "GET")
die ( "You can only reach this page by posting from the html form" );
if (($_GET ["txtCaptcha"] == $_SESSION ["security_code"]) && (! empty ( $_GET ["txtCaptcha"] ) && ! empty ( $_SESSION ["security_code"] ))) {
echo "true";
} else {
echo "false";
}
?>
My problem might due to the response format it is not true or false, but i print out whole verifyCap code. Anyone can help?
An ajax request does an get by default instead of a post. Change:
if ($_SERVER ["REQUEST_METHOD"] != "POST")
to
if ($_SERVER ["REQUEST_METHOD"] != "GET")
besides that, do not use $_REQUEST to get your data. Use $_GET instead.
You could also add some settings your ajax request:
type: "POST",
data: "your params here",
You're receiving the whole verifyCap.php code because your PHP isn't interpreted by your web server.
In your verifyCap.php you are using the short tag notation (<? //code ?>).
Not all server uses this php extension, and it is considered deprecated. If your webserver doesn't use this extension, then your code is considered as an XML document, as XML document always start with <? <!-- some XML here --> ?>.
Use <?php //code ?> and your problem should be fixed.
Also, following #XpertEase answer isn't a bad idea either.
Edit: More info on PHP short tags Are PHP short tags acceptable to use? (via #XpertEase)

jQuery.ajax / CodeIgniter (PHP) : Returning TRUE/FALSE in PHP, how can I get jQuery to see this?

I've built a function for checking a username. I'm using it as a callback for form validation in CodeIgniter, and it works nicely. However, I'd like to also use it with AJAX to check on the fly if the user has JS enabled. So my controller has this:
function check_username($s = FALSE)
{
if ($s):
$this->db_common->like('username', $s);
$query = $this->db_common->get('users');
if ($query->num_rows() > 0):
$this->form_validation->set_message('check_username', 'Username taken. Choose another!');
return FALSE;
else:
return TRUE;
endif;
else:
echo 'Username required';
endif;
}
And my HTML/JS is this:
$(document).ready(function()
{
var delayed;
$("#username").keyup(function()
{
clearTimeout(delayed);
var value = this.value;
if (value)
{
delayed = setTimeout(function() {
$.ajax
({
type: "POST",
url: "<?php echo base_url(); ?>auth/check_username/",
data: $("#username").val(),
success: function(html)
{
$("#username_check").html(html);
}
});
}, 100);
}
});
});
Basically, I'm returning FALSE if the username exists and TRUE if it does exist. How do I get my jQuery AJAX to see that? Basically, I want jQuery to check if it's false, then say 'username exists' and if it's true, then 'username is okay'.
Do something like the following:
echo 'ok';
return TRUE;
The reason for this is that jQuery can't see the boolean values returned by PHP as they're not send to the browser's output.
Basically, I'm returning FALSE if the username exists and TRUE if it does exist. How do I get my jQuery AJAX to see that?
You can't directly. I would output 0 or 1 instead.
I would return true or false as JSON boolean from your PHP script and use javascript's eval() function to evaluate that to a javascript var.
There is a way to do it with PHP and jQuery. Here is an example...
simply have your php script echo back true or false.
PHP-> echo true; or echo false;
$.post("your_url/your_class/your_method", { } ,
function(data) {
if(data) alert('true');
else alert('false');
}, "json")
.error(function() { //alert("an AJAX error occurred!");
});

jquery validation plugin and check unique field?

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.

Categories