Solved

jQuery Validation Help

Posted on 2011-09-19
9
349 Views
Last Modified: 2012-05-12
The issue is on the vpnrequest.php using the validation plugin remote call it checks to ensure the employee id is valid from the database.  If it is valid the checkempid.php 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 but the info will change automatically if I enter in a new valid empID.  The form will not submit because the empID field will not validate.  If I return just ‘true’ from the checkempid.php it will validate fine as well just without any autofilled form information.

If I instead use the success: function and enter in a valid userid it will fill the form out and submit the form, however if it is incorrect or if you enter a new id in it will not resubmit to the remote function call.  
Here is the jquery code with the Complete: function intact.
$(document).ready(function() {
                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);
                                        return success;
                                    }
                                }
                            }
                        }
                    },
                    messages: {
                        empID:{
                            required: "This field is required",
                            remote: "Invalid Employee ID"
                        }
                    }
                });

Open in new window


Here is the php file with the json encode.
 
<?php

include("class.employee.php");
$employee = new Employee(); //instantiate new employee obj
$empID = $_REQUEST['empID']; //get the emp id from ajax form
$valid = $employee->checkEmpID($empID); //check to ensure emp# exists
if ($valid == 'true') {
    $string = array();
    //Get employee fname, lname
    $info = $employee->getEmpInfo($empID);
    while ($row = mysql_fetch_array($info)) {
        //get supervisor info
        $supervisorInfo = $employee->getSupervisorInfo($row['empSupervisorID']);
        while ($row1 = mysql_fetch_array($supervisorInfo)) {
            $superFName = ucwords(strtolower($row1['empFirstName']));
            $superLName = ucwords(strtolower($row1['empLastName']));
        }
        //get the facility info
        $facilityNameQry = $employee->getFacilityName($row['empEPlant']);
        while ($row2 = mysql_fetch_array($facilityNameQry)){
            $facilityName = $row2['facilityName'];
        }
        //create json array return
        $string[success] = $valid;
        $string[status] = $valid;
        $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 {
    echo $valid;
}
?>

Open in new window

0
Comment
Question by:PhillipsPlastics
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 5
  • 4
9 Comments
 
LVL 7

Expert Comment

by:Swafnil
ID: 36565754
There is an error in your PHP file, you are not setting the status code you are checking in JS and the JS file could be optimized a bit. I'll start with the JS file:

$(document).ready(function() {
                $('#vpnRequest').validate({
                    rules: {
                        empID: {
                            required: true,
                            minlength: 4,
                            remote: {
                                url: "checkEmpID.php",
				dataType: "json", // response will be JSON-encoded
                                success: function(data) {
                                    if (data.success == false){
                                        return false;
                                    } else {
                                        $('#fName').val(data.fName);
                                        $('#lName').val(data.lName);
                                        $('#superName').val(data.supervisorFName+" "+data.supervisorLName);
                                        $('#facilityName').val(data.facilityName);
                                        return true;
                                    }
                                }
                            }
                        }
                    },
                    messages: {
                        empID:{
                            required: "This field is required",
                            remote: "Invalid Employee ID"
                        }
                    }
                });
	});

Open in new window


and the modified PHP file (I removed the status code because it was somehow duplicate with the success variable):

<?php
include("class.employee.php");
$employee = new Employee(); //instantiate new employee obj
$empID = $_GET['empID']; //get the emp id from ajax form
$valid = $employee->checkEmpID($empID); //check to ensure emp# exists
if ($valid == 'true') {
    $string= array();
    // Get employee fname, lname
    $info = $employee->getEmpInfo($empID);
	if ($info && mysql_num_rows($info)>0) {
		$row = mysql_fetch_array($info);
		//get supervisor info
		$supervisorInfo = $employee->getSupervisorInfo($row['empSupervisorID']);
		if ($supervisorInfo && mysql_num_rows($supervisorInfo)>0) {
			$row1 = mysql_fetch_array($supervisorInfo);
			$superFName = ucwords(strtolower($row1['empFirstName']));
			$superLName = ucwords(strtolower($row1['empLastName']));
		}
		//get the facility info
		$facilityNameQry = $employee->getFacilityName($row['empEPlant']);
		while ($row2 = mysql_fetch_array($facilityNameQry)){
			$facilityName = $row2['facilityName'];
		}
		//create json array return
		$string['success'] = true;
		$string['fName'] = ucwords(strtolower($row['empFirstName']));
		$string['lName'] = ucwords(strtolower($row['empLastName']));
		$string['supervisorFName'] = $superFName;
		$string['supervisorLName'] = $superLName;
		$string['facilityName'] = $facilityName;
	} else {
		echo $string['success'] = false;
	}
} else {
    echo $string['success'] = false;
}
$response = json_encode($string);
echo $response;
?>

Open in new window


I couldn't test the code but I hope it'll work as expected ;-)

Regards, Sascha
0
 
LVL 7

Expert Comment

by:Swafnil
ID: 36565769
Doh, remove the echo()s from the lower else branches. Btw, calling an array variable "$string" is a bit odd ...
0
 

Author Comment

by:PhillipsPlastics
ID: 36566431
Thanks for the response, unfortunately using the success: function works only if you enter a valid userid the first time and then it breaks, not allowing for another reentry should you want a different userid or a valid one.  The only way this code works is using the complete: function but using that function although it works as expected it will not finish the remote validation for the empID field, it will always remain invalid even if it is not and has populated the rest of the text fields.

The returns were a shot in the dark, as was the extra success and valid json string elements to see if I could stumble upon whatever the remote: function is wanting to validate for.  If you have any other ideas I would be grateful.  Thanks again.
0
Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
LVL 7

Expert Comment

by:Swafnil
ID: 36566662
Could you also post the form you designed? I would like to see the complete set up, otherwise I can only continue guessing what could be wrong. Have you checked if your Javascript console gives you any errors (i.e. through using Firebug or Chrome's debugger)?

There should be no difference if you use complete() or success(): if your backend will return a 200 code, both success() and complete() can be used.
0
 

Author Comment

by:PhillipsPlastics
ID: 36566857
The 3 files I used are attached, also I am using newest jquery (1.6.4) and the form validation from http://bassistance.de/
vpnRequest.php.txt
class.employee.php.txt
checkEmpID.php.txt
0
 
LVL 7

Expert Comment

by:Swafnil
ID: 36568360
I just debugged your code and I don't know why, the validation process fails when checking conditions for the remote validator; this may be due to a bug in in the validator plugin, but I'm still not sure where exactly the error happens. I will get back to you as soon as I find the errornous portion of the validator.
0
 

Accepted Solution

by:
PhillipsPlastics earned 0 total points
ID: 36568597
Think I found a solution... http://plugins.jquery.com/content/custom-function-handle-returned-data-remote-function

Adding

if ($.isFunction(param.validateResult)) response = param.validateResult(response);

to the validator code itself and then instead of calling complete call validateResult appears to work.  Not sure how to test for fringe cases but it seems to work off the cuff testing I just did.
0
 
LVL 7

Expert Comment

by:Swafnil
ID: 36570356
That's good to hear! Still it's strange that the original code did not work properly which may be due to inconsistencies in the different JQuery versions.
0
 

Author Closing Comment

by:PhillipsPlastics
ID: 36594790
Found the solution.
0

Featured Post

SharePoint Admin?

Enable Your Employees To Focus On The Core With Intuitive Onscreen Guidance That is With You At The Moment of Need.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Since pre-biblical times, humans have sought ways to keep secrets, and share the secrets selectively.  This article explores the ways PHP can be used to hide and encrypt information.
Boost your ability to deliver ambitious and competitive web apps by choosing the right JavaScript framework to best suit your project’s needs.
The viewer will learn how to dynamically set the form action using jQuery.
The viewer will learn how to create a basic form using some HTML5 and PHP for later processing. Set up your basic HTML file. Open your form tag and set the method and action attributes.: (CODE) Set up your first few inputs one for the name and …

738 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question