My issue using the validation plugin is with the remote call specifically.
The remote checks to ensure the employee id is valid from the db. If it is valid then it returns a json string with the employee info (first name, last name, supervisor name, and facility name).
The issue is if I return that json string using the complete: function the empid field stays invalid with the error class, and will not allow the form to submit even though everything is valid. If I just return true from the remote call the empID field is valid and the form will submit (assuming the other fields are completed).
Is there a specific parameter in the json callback that needs to be set to true for the remote: call to finish and be true? I am lost as to how to fix this problem, so any help would be much appreciated! See below for the related code.
var ajax_data = new Object;
$('#vpnRequest').validate({
rules: {
empID: {
//required: true,
//minlength: 4,
remote: {
url: "checkEmpID.php",
dataFilter: function(data) { ajax_data = data; return data;},
complete: function() {
var jsonObj = new Object;
jsonObj = jQuery.parseJSON(ajax_data);
var success = jsonObj.status;
if(success == 'false'){
//return success;
}else if(success == 'true'){
$('#fName').val(jsonObj.fName);
$('#lName').val(jsonObj.lName);
$('#superName').val(jsonObj.supervisorFName+" "+jsonObj.supervisorLName);
$('#facilityName').val(jsonObj.facilityName);
$('#empID').addClass('stuff');
$('#empID').removeClass('stuff');
//return success;
}
}
}
}
},
messages: {
empID:{
required: "This field is required",
remote: "Invalid Employee ID"
}
}
});
PHP file empID checker:
$string[status] = 'true';
$string[fName] = ucwords(strtolower($row['empFirstName']));
$string[lName] = ucwords(strtolower($row['empLastName']));
$string[supervisorFName] = $superFName;
$string[supervisorLName] = $superLName;
$string[facilityName] = $facilityName;
}
$response = json_encode($string);
echo $response;
} else {
$response = json_encode($valid);
echo $response;
}
Adding to the validator code itself:
if ($.isFunction(param.validateResult)) response = param.validateResult(response);
from the site http://plugins.jquery.com/content/custom-function-handle-returned-data-remote-function appears to work extremely well, as it validates properly and submits the form. If anyone wants to test further to ensure fringe cases that would be great but this should definitely be added to the validator plugin to extend its capabilities.
Related
This question already has answers here:
How to respond to jQuery Validation remote?
(1 answer)
jQuery Validate remote method usage to check if username already exists
(2 answers)
Closed 2 years ago.
I'm using the jQuery validator's remote method to determine if an email address already exists in our SaaS platform.
The code below is what we are using and it's fine. However, we would like to ideally return some information about the existing user, so that we may display a link to the existing patient's profile.
I've scoured the validator docs and can't seem to find any way to handle return parameters other than true/false. Is this a limitation of the remote method?
jQuery
form.validate({
rules: {
email: {
remote: {
url: "CheckEmailExists.php",
type: "post"
}
}
},
messages: {
email: {
remote: "This email address is already assigned to an existing patient"
}
},
});
PHP
$existingUserQuery = "SELECT tbl_patients.patient_id FROM tbl_patients WHERE tbl_patients.patient_email = :email";
$getUser = $pdo->prepare($existingUserQuery);
$getUser->bindparam(":email", $email);
$getUser->execute();
$numCount = $getUser->rowCount();
if ($numCount > 0) {
echo 'false';
} else {
echo 'true';
}
You can create a custom method and within the method do run your own remote call via AJAX. Then in your php, return a JSON object with the values that you want to use.
jQuery.validator.addMethod("validatemmail", function(value, element) {
var _is_valid = false;
var qry = {"email" : value};
$.ajax({
type: "POST",
url: "CheckEmailExists.php",
data: qry,
done: function(data){
if(data.error == "new"){
_is_valid = true;
console.log(data.patient_name);
}
else{
_is_valid = false;
}
return this.optional(element) || _is_valid );
}
});
}, "This email address is already assigned to an existing patient");
$('validatorElement').validate({
rules : {
email : { validatemmail : true }
}
});
Your PHP:
$return = [];
if ($numCount > 0) {
$return["error"] = "exists";
$return["patient_name"] = "John";
} else {
$return["error"] = "new";
}
header('Content-Type: application/json');
echo json_encode($return);
The original idea:
jQuery Validate Plugin - How to create a simple custom rule?
I have been using php and ajax to validate if an email inserted in my form exists in my database.
I am using jquery to send the email value to my php file and return a message if the email is found. My code is working fine but I want if an email is found the cursor be on focus on the #usu_email field until the email be changed. After this, it should allow me to continue to next field.
This is the jquery code I am using:
function getemail(value) {
var usumail = $("#usu_email").val();
$.ajax({
type: "POST",
url: "ajax_email.php",
data: "usu_email=" + usumail,
success: function(data, textStatus) {
if (data !== null) {
$("#eresult").html(data);
$("#usu_email").focus();
}
},
});
};
My problem is that if and email does not exist in my database the cursor keeps doing focus on my #usu_email field and does not allow me to continue to next field.
I will appreciate any help about this problem because I know very little about jquery.
First... Your condition if (data !== null) always will be true since there always will be a data provided... Be it an empty string.
The only case where there will be no data is on Ajax error... And the condition won't even be evaluated because the success callback won't execute.
Next, I assume that your Ajax request is triggered on $("#usu_email") blur... Else, I don't know how you achieve «does not allow me to continue».
Modify it in this way to compare a response:
function getemail(value) {
var usumail = $("#usu_email").val();
$.ajax({
type: "POST",
url: "ajax_email.php",
data: "usu_email=" + usumail,
datatype: "json",
success: function(data) { // There is only one argument here.
// Display the result message
$("#eresult").html(data.message);
if (data.email_exist == "yes") {
$("#usu_email").focus();
}
if (data.email_exist == "no") {
// Something else to do in this case, like focussing the next field.
}
},
});
};
On the PHP side, you have to provide the json response. It would look like something like this:
<?php
// You have this variable to compare against the database
$email = $_POST[usu_email];
// You say it is working.
// ...
// Then, you certainly have a result... Say it's $found (true/false).
// Build an array of all the response param you want to send as a response.
if($found){
$result[email_exist] = "yes";
$result[message] = "The submitted email already exist.";
}else{
$result[email_exist] = "no";
$result[message] = "A success message about the email here.";
}
// Add this header to the returned document to make it a valid json that doesn't need to be parsed by the client-side.
header("Content-type:application/json");
// Encode the array as a json and print it. That's what is sent in data as an Ajax response.
echo json_encode($result);
?>
Be carefull not to echo anything else. Not even a blank space or a line return.
Depends on what type of data you're expecting (simple text response or JSON), but at first i would start to replace your if(data !== null) with if(typeof data != "undefined" && data !== null && data != "") because the returned response might just be empty and not NULL.
If it doesn't work you should consider adding your php code to the question so we can figure out exactly what it returns when no matching email is found.
I have a very strange problem and couldn't figure it out. I am working with AJAX/PHP and fetching the data from mysql database on user interaction by ajax call. Everything is working very fine and no problem at all. But only one issue which is persisting is when the data is not found in mysql database, then a user-friendly message is not returned from the server ajax file - the one part works and other doesn't. Here is my code -
This is my first file where the form reside (full code is not there; only js code) -
<script type="text/javascript">
$(document).ready(function(){
$("#selcustomer").change(function(){
var customers_id = $(this).val();
if(customers_id > 0)
{
$.ajax({
beforeSend: startRequest,
url: "ajax/ajax.php",
cache: false,
data: "customers_id="+customers_id,
type: "POST",
dataType: "json",
success: function(data){
if(data != "No result found.")
{
$("#img_preloader").hide();
$("#error").html('');
// $("#txtfname").val(data.fname);
// $("#txtlname").val(data.lname);
for(var key in data)
{
document.getElementById("txt"+key).value = data[key];
}
}
else
{
$("#img_preloader").hide();
$("#error").html(data);
$("input").each(function(){
$(this).val('');
});
}
}
});
}
else
{
$("#error").html('');
$("input").each(function(){
$(this).val('');
});
}
});
});
function startRequest()
{
$("#img_preloader").show();
}
</script>
And this is my server-side ajax file (php file) which interacts with database -
<?php
include("../includes/db-config.php");
if(isset($_POST["customers_id"]))
{
$customers_id = $_POST["customers_id"];
$query = "SELECT * FROM `tb_customers` WHERE `customers_id` = '$customers_id'";
$rs = mysql_query($query);
if(mysql_num_rows($rs) > 0)
{
$row = mysql_fetch_array($rs);
$customers_first_name = $row['customers_first_name'];
$customers_last_name = $row['customers_last_name'];
$customers_email_id = $row['customers_email_id'];
$customers_phone_no = $row['customers_phone_no'];
$customers_address_line_1 = $row['customers_address_line_1'];
$customers_address_line_2 = $row['customers_address_line_2'];
$customers_country = $row['customers_country'];
$data = array('fname' => $customers_first_name, 'lname' => $customers_last_name, 'emailid' => $customers_email_id, 'phoneno' => $customers_phone_no, 'addressline1' => $customers_address_line_1, 'addressline2' => $customers_address_line_2, 'country' => $customers_country);
echo json_encode($data);
}
else
{
echo "No result found.";
}
}
?>
The if part is working fine but when no data is found in database the else part is not sending the data back to jQuery code. I checked in browser console and saw the else part is returning the response but the jquery code in success: part of $.ajax is not running - neither within if, nor in else and also not outside of if/else. I mean to say that a simple alert is not fired with data under success when no data is found in mysql database. But when i remove all the data in ajax/php file and say simply write 123 then alert comes with 123 but not when the actual code is there. Can you plz tell me what is the issue behind this strange problem?
Your datatype is set to JSON in your AJAX call, so the return value must be a valid JSON.
When you are encountering the else condition, you are returning something that is not JSON.
Try this -
else
{
echo json_encode("No result found.");
}
Or something more flexible-
else{
echo json_encode(Array("err"=>"No result found."));
}
EDIT-
...But when i remove all the data in ajax/php file and say simply write
123 then alert comes with 123...
That is because a 123 (number) is valid JSON. Instead of 123, try writing No result and an error would be thrown, because No result (a string) needs quotes(which is taken care when you use json_encode).
I just was wondering what you guys could recommend / suggest for an approach I am trying to take. I am trying to make my own simple Live Support chat system and need to make a feature for the Client to view when the Agent is typing a message. I've figured out how to do it for the person typing themselves but not for a remote person.
Please help as I am not very great at jQuery! Heres my current code that simply shows when you are typing in a input field with id of #chatMessage. Please note, this is a PHP, MySQL & jQuery chat system.
$('#chatMessage').keyup(function(){
if ($("#chatMessage").val() == ''){
$('#typing').html('');
}else{
$('#typing').html('The agent is typing a message..');
}
});
Thanks
You only need to add an ajax call to the server and then a timer on the client that checks for agent status...
// Agent side..
function checkStatus(){
jQuery.get('/server-url?agent_id=32&status', function(data){
if (data.status == 'typing')
$('#typing').html('The user/client is typing a message..');
else
$('#typing').html('');
checkStatus();
});
}
// Start the function begining.
setTimeout(checkStatus, 300);
var agent_timer;
$('#chatMessage').keyup(function(){
if (agent_timer)
clearTimeout(agent_timer);
if ($("#chatMessage").val() == ''){
status = 'empty';
} else {
status = 'writing';
}
agent_timer = setTimeout(function(){
// Send status to server php script
$.post('/server-url?agent_id=23', {status: status}, function(data){
// handle response
});
}, 400);
});
// Server side...
// check for agent, and other things...
if (isset($_GET['agent_id'])){
// Agent server side
if (isset($_POST['status']){
// Save status to database
$this->save(array('agent' => $agent, 'chat_id' => $chat_id, 'status' => $_POST['status']));
}
if (isset($_GET['status'])){
$data = $this->read(array('agent_id' => $chat_id));
}
} else {
// This is the client server side
if (isset($_GET['status'])) {
$data = $this->read(array('chat_id' => $chat_id));
return $data['status'];
}
}
// handle other things and return data if necessary
// echo json_encode($data);
// Client side JS
function checkStatus(){
jQuery.get('/server-url?chat_id=32&status', function(data){
if (data.status == 'typing')
$('#typing').html('The agent is typing a message..');
else
$('#typing').html('');
checkStatus();
});
}
// Start the function at begining.
setTimeout(checkStatus, 300);
// We can do the same, so the agent can know if user is typing too (you must also copy the above function)
var client_timer;
$('#chatMessage').keyup(function(){
if (client_timer) clearTimeout(client_timer);
if ($("#chatMessage").val() == ''){
status = 'empty';
} else {
status = 'writing';
}
client_timer = setTimeout(function(){
// Send status to server php script
$.post('/server-url?chat_id=23', {status: status}, function(data){
// handle response
});
}, 400);
});
Maybe there are better ways than updating a row in mysql... but I can't think one now..
I really was trying to avoid asking this question. I have seen quite a few posts on SO regarding this plugin but they still didn't quite get it for me. Right now I have a new account registration form and I'm trying to write a custom method for validating a unique username. I would like to think that the following should work:
$.validator.addMethod(
"uniqueUsername",
function(value, element) {
$.post(
"http://" + location.host + "/scripts/ajax/check_username.php",
{
username: value
},
function(response) {
if(response == 'true') {
return true;
} else {
return false;
}
}
);
},
"This username is already taken."
);
Unfortunately it seems like the plugin moves on regardless of the callback function. I found someone suggest doing something like the following:
var result = false;
$.validator.addMethod(
"uniqueUsername",
function(value, element) {
$.post(
"http://" + location.host + "/scripts/ajax/check_username.php",
{
username: value
},
function(response) {
if(response == 'true') {
result = true;
} else {
result = false;
}
}
);
return result;
},
"This username is already taken."
);
But it seems to have a delay since it stores the value, then on the next event will set whatever the value is. What do you guys recommend?
Since this is an asynchronous check, there needs to be more around it (you can't return a value from a function like this, it'll always be false in your case). The built-in method is remote, used like this:
$("form").validate({
rules: {
username: {
remote: {
url: "http://" + location.host + "/scripts/ajax/check_username.php",
type: "post"
}
}
}
});
This will POST a username: valueofElement since the rule is for the element named username. Your server-side script should return true if the validation should pass, false otherwise...so false if the user name is already taken.
You can read more about the remote option here, including how to pass additional data arguments if needed.
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');
}
}