Go Premium for a chance to win a PS4. Enter to Win

x
?
Solved

jQuery Validation Help

Posted on 2011-09-19
9
Medium Priority
?
381 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
  • 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
Concerto Cloud for Software Providers & ISVs

Can Concerto Cloud Services help you focus on evolving your application offerings, while delivering the best cloud experience to your customers? From DevOps to revenue models and customer support, the answer is yes!

Learn how Concerto can help you.

 
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

Independent Software Vendors: 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!

Question has a verified solution.

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

This article discusses four methods for overlaying images in a container on a web page
This article demonstrates how to create a simple responsive confirmation dialog with Ok and Cancel buttons using HTML, CSS, jQuery and Promises
Learn how to match and substitute tagged data using PHP regular expressions. Demonstrated on Windows 7, but also applies to other operating systems. Demonstrated technique applies to PHP (all versions) and Firefox, but very similar techniques will w…
Explain concepts important to validation of email addresses with regular expressions. Applies to most languages/tools that uses regular expressions. Consider email address RFCs: Look at HTML5 form input element (with type=email) regex pattern: T…
Suggested Courses

824 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