Jump to content

Form Validation With Success Message On Record Save


hobbiton73

Recommended Posts

I wonder whether someone may be able to help me please.

 

Using this http://www.position-absolute.com/articles/jquery-form-validator-because-form-validation-is-a-mess/ and this http://net.tutsplus.com/tutorials/javascript-ajax/building-a-sleek-ajax-signup-form/ tutorials, I've put together this http://www.mapmyfinds.co.uk/chris/test2.php page which performs 'field' validation, then, upon the 'Save' button being clicked by the user, displays a AJAX status message telling the user whether the record has been saved or not.

 

The problem I'm having is that although the fields are correctly validated i.e. if the fields are blank, the correct validation error messages are displayed on screen, the AJAX message says that the 'Record has been saved' and the record is added to a mySQL database, so in essence creating a blank record.

 

I'm having great difficulty in joining the 'Validation' and the 'Record Saved' message.

 

I've run this through JavaScript Console and unfortunately there are no errors shown, so I have to be honest and say that I'm really not sure where the problem lies.

 

This is the code which activates the AJAX message:

 

<script type="text/javascript">
	jQuery(document).ready(function(){
		// binds form submission and fields to the validation engine
		jQuery("#addlocation").validationEngine();
	})
</script>
<script type="text/javascript">
$(document).ready(function(){
$('#addlocation').submit(function(){

	//check the form is not currently submitting
	if($(this).data('formstatus') !== 'submitting'){

		//setup variables
		var form = $(this),
			formData = form.serialize(),
			formUrl = form.attr('action'),
			formMethod = form.attr('method'), 
			responseMsg = $('#saverecordresponse');

		//add status data to form
		form.data('formstatus','submitting');

		//show response message - waiting
		responseMsg.hide()
				   .addClass('response-waiting')
				   .text('Please Wait...')
				   .fadeIn(200);

		//send data to server for validation
		$.ajax({
			url: formUrl,
			type: formMethod,
			data: formData,
			success:function(data){

				//setup variables
				var responseData = jQuery.parseJSON(data), 
					klass = '';

				//response conditional
				switch(responseData.status){
					case 'error':
						klass = 'response-error';
					break;
					case 'success':
						klass = 'response-success';
					break;	
				}

				//show reponse message
				responseMsg.fadeOut(200,function(){
					$(this).removeClass('response-waiting')
						   .addClass(klass)
						   .text(responseData.message)
						   .fadeIn(200,function(){
							   //set timeout to hide response message
							   setTimeout(function(){
								   responseMsg.fadeOut(300,function(){
								       $(this).removeClass(klass);
									   form.data('formstatus','idle');
								   });
							   },2000)
							    setTimeout(function() { 
							 	$('body').fadeOut(400, function(){
							 	location.reload();
								setTimeout(function(){
							    $('body').fadeIn(400);
								 }, 500);
								 window.scrollTo(x-coord, y-coord);
							 });
						}, 2000);							
					});
				});
			}
		});
	}

	//prevent form from submitting
	return false;
});
});
</script>

 

and the following code is the PHP script which saves the record.

 

<?php
    
    		$userid = $_POST['userid'];
    		$locationname = $_POST['locationname'];
    		$returnedaddress = $_POST['returnedaddress'];
    		$osgb36lat = $_POST['osgb36lat'];
    		$osgb36lon = $_POST['osgb36lon'];
    		$nameofcontact = $_POST['nameofcontact'];
    		$address1 = $_POST['address1'];
    		$address2 = $_POST['address2'];
    		$address3 = $_POST['address3'];
    		$address4 = $_POST['address4'];
    		$address5 = $_POST['address5'];
    		$telephonenumber = $_POST['telephonenumber'];
    		
    			$query = mysql_query("INSERT INTO `table` (userid, locationname, returnedaddress, osgb36lat, osgb36lon, nameofcontact, address1, address2, address3, address4, address5, telephonenumber) VALUES ('$userid', '$locationname', '$returnedaddress', '$osgb36lat', '$osgb36lon', '$nameofcontact', '$address1', '$address2', '$address3', '$address4', '$address5', '$telephonenumber')");  
    			if($query){ //if insert is successful
    				$status = "success";
    				$message = "Location Saved!";	
    			}
    			else { //if insert fails
    				$status = "error";
    				$message = "There was a problem in saving the record. Please try again!";	
    			}	
    
    			//return json response
    				$data = array(
    					'status' => $status,
    					'message' => $message
    				);
    				
    				echo json_encode($data);
    				exit;
    
    ?>

 

 

I just wondered whether someone could have a look at this please and let me know where I'm going wrong?

 

Many thanks and kind regards

Link to comment
Share on other sites

You've done the exact opposite of what you should have done. Client-side validation isn't secure at all, as it would only take someone turning off their JS to be able to circumvent it.

Always do the validation server-side, with the proper validation functions, and you won't have this problem.

 

Not to mention that you need to escape the output going into the query, to prevent SQL injections.

 

PS: For the JS issue, I think you want to look at "preventDefault ()". Didn't look at the JS too closely though, as the lack of server-side validation is a much bigger issue.

Link to comment
Share on other sites

Hi ChristianF, thank you very much for taking the time to reply to my post.

 

I am very new to  this, so I've obviously made some errors. Could you perhaps elaborate how I may achieve this on the 'server' rather than the 'client' side.

 

Many thanks and kind regards

 

 

Link to comment
Share on other sites

Yes, validate the input in the PHP code. Pretend as if JS doesn't exist. You'll need to use the ctype functions and possibly Regular Expressions, plus functions like intval () and similar. Which means you'll have to know and plan what kind of input you are expecting from your form, including all of the possible legal permutations that might occur.

 

Also took a second look at the JavaScript that you have, and saw this comment:

//send data to server for validation

 

So, basically what you have is just half of the code. You're still missing the actual validation.

 

I also suspect that you only need one of the two JS blocks you've posted, and that you're not using the validationEngine bindings.

Link to comment
Share on other sites

Hi @ChristianF, I hope you are well.

 

I wonder whether you may be able to help me please.

 

Following on from your much appreciated advice yesterday, I went away to research 'Server' side validation. I found that the tutorial I was using did cater for this here http://www.position-absolute.com/articles/using-form-ajax-validation-with-the-jquery-validation-engine-plugin/.

 

I've been working through the 'Inline' demo, but I wonder whether you may be able to help me please with a few things I'm not too clear about.

 

The demo deals with 3 PHP files (shown below) in conjunction with main HTML page.

 

jquery.validationEngine-en.js

 

(function($){
    $.fn.validationEngineLanguage = function(){
    };
    $.validationEngineLanguage = {
        newLang: function(){
            $.validationEngineLanguage.allRules = {
                "required": { // Add your regex rules here, you can take telephone as an example
                    "regex": "none",
                    "alertText": "* This field is required",
                    "alertTextCheckboxMultiple": "* Please select an option",
                    "alertTextCheckboxe": "* This checkbox is required",
                    "alertTextDateRange": "* Both date range fields are required"
                },
                "requiredInFunction": { 
                    "func": function(field, rules, i, options){
                        return (field.val() == "test") ? true : false;
                    },
                    "alertText": "* Field must equal test"
                },
                "dateRange": {
                    "regex": "none",
                    "alertText": "* Invalid ",
                    "alertText2": "Date Range"
                },
                "dateTimeRange": {
                    "regex": "none",
                    "alertText": "* Invalid ",
                    "alertText2": "Date Time Range"
                },
                "minSize": {
                    "regex": "none",
                    "alertText": "* Minimum ",
                    "alertText2": " characters allowed"
                },
                "maxSize": {
                    "regex": "none",
                    "alertText": "* Maximum ",
                    "alertText2": " characters allowed"
                },
			"groupRequired": {
                    "regex": "none",
                    "alertText": "* You must fill one of the following fields"
                },
                "min": {
                    "regex": "none",
                    "alertText": "* Minimum value is "
                },
                "max": {
                    "regex": "none",
                    "alertText": "* Maximum value is "
                },
                "past": {
                    "regex": "none",
                    "alertText": "* Date prior to "
                },
                "future": {
                    "regex": "none",
                    "alertText": "* Date past "
                },	
                "maxCheckbox": {
                    "regex": "none",
                    "alertText": "* Maximum ",
                    "alertText2": " options allowed"
                },
                "minCheckbox": {
                    "regex": "none",
                    "alertText": "* Please select ",
                    "alertText2": " options"
                },
                "equals": {
                    "regex": "none",
                    "alertText": "* Fields do not match"
                },
                "creditCard": {
                    "regex": "none",
                    "alertText": "* Invalid credit card number"
                },
                "phone": {
                    // credit: jquery.h5validate.js / orefalo
                    "regex": /^([\+][0-9]{1,3}[\ \.\-])?([\(]{1}[0-9]{2,6}[\)])?([0-9\ \.\-\/]{3,20})((x|ext|extension)[\ ]?[0-9]{1,4})?$/,
                    "alertText": "* Invalid phone number"
                },
                "email": {
                    // HTML5 compatible email regex ( http://www.whatwg.org/specs/web-apps/current-work/multipage/states-of-the-type-attribute.html#    e-mail-state-%28type=email%29 )
                    "regex": /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$/,
                    "alertText": "* Invalid email address"
                },
                "integer": {
                    "regex": /^[\-\+]?\d+$/,
                    "alertText": "* Not a valid integer"
                },
                "number": {
                    // Number, including positive, negative, and floating decimal. credit: orefalo
                    "regex": /^[\-\+]?((([0-9]{1,3})([,][0-9]{3})*)|([0-9]+))?([\.]([0-9]+))?$/,
                    "alertText": "* Invalid floating decimal number"
                },
                "date": {                    
                    //	Check if date is valid by leap year
		"func": function (field) {
				var pattern = new RegExp(/^(\d{4})[\/\-\.](0?[1-9]|1[012])[\/\-\.](0?[1-9]|[12][0-9]|3[01])$/);
				var match = pattern.exec(field.val());
				if (match == null)
				   return false;

				var year = match[1];
				var month = match[2]*1;
				var day = match[3]*1;					
				var date = new Date(year, month - 1, day); // because months starts from 0.

				return (date.getFullYear() == year && date.getMonth() == (month - 1) && date.getDate() == day);
			},                		
		 "alertText": "* Invalid date, must be in YYYY-MM-DD format"
                },
                "ipv4": {
                    "regex": /^((([01]?[0-9]{1,2})|(2[0-4][0-9])|(25[0-5]))[.]){3}(([0-1]?[0-9]{1,2})|(2[0-4][0-9])|(25[0-5]))$/,
                    "alertText": "* Invalid IP address"
                },
                "url": {
                    "regex": /^(https?|ftp):\/\/(((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|*@)?(((\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5]))|((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?)(:\d*)?)(\/((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)+(\/(([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)*)*)?)?(\?((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|[\uE000-\uF8FF]|\/|\?)*)?(\#((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|\/|\?)*)?$/i,
                    "alertText": "* Invalid URL"
                },
                "onlyNumberSp": {
                    "regex": /^[0-9\ ]+$/,
                    "alertText": "* Numbers only"
                },
                "onlyLetterSp": {
                    "regex": /^[a-zA-Z\ \']+$/,
                    "alertText": "* Letters only"
                },
                "onlyLetterNumber": {
                    "regex": /^[0-9a-zA-Z]+$/,
                    "alertText": "* No special characters allowed"
                },
                // --- CUSTOM RULES -- Those are specific to the demos, they can be removed or changed to your likings
                "ajaxUserCall": {
                    "url": "ajaxValidateFieldUser",
                    // you may want to pass extra data on the ajax call
                    "extraData": "name=eric",
                    "alertText": "* This user is already taken",
                    "alertTextLoad": "* Validating, please wait"
                },
			"ajaxUserCallPhp": {
                    "url": "phpajax/ajaxValidateFieldUser.php",
                    // you may want to pass extra data on the ajax call
                    "extraData": "name=eric",
                    // if you provide an "alertTextOk", it will show as a green prompt when the field validates
                    "alertTextOk": "* This username is available",
                    "alertText": "* This user is already taken",
                    "alertTextLoad": "* Validating, please wait"
                },
                "ajaxNameCall": {
                    // remote json service location
                    "url": "ajaxValidateFieldName",
                    // error
                    "alertText": "* This name is already taken",
                    // if you provide an "alertTextOk", it will show as a green prompt when the field validates
                    "alertTextOk": "* This name is available",
                    // speaks by itself
                    "alertTextLoad": "* Validating, please wait"
                },
			 "ajaxNameCallPhp": {
                    // remote json service location
                    "url": "phpajax/ajaxValidateFieldName.php",
                    // error
                    "alertText": "* This name is already taken",
                    // speaks by itself
                    "alertTextLoad": "* Validating, please wait"
                },
                "validate2fields": {
                    "alertText": "* Please input HELLO"
                },
            //tls warning:homegrown not fielded 
                "dateFormat":{
                    "regex": /^\d{4}[\/\-](0?[1-9]|1[012])[\/\-](0?[1-9]|[12][0-9]|3[01])$|^(??:(?:0?[13578]|1[02])(\/|-)31)|(??:0?[1,3-9]|1[0-2])(\/|-)(?:29|30)))(\/|-)(?:[1-9]\d\d\d|\d[1-9]\d\d|\d\d[1-9]\d|\d\d\d[1-9])$|^(??:0?[1-9]|1[0-2])(\/|-)(?:0?[1-9]|1\d|2[0-8]))(\/|-)(?:[1-9]\d\d\d|\d[1-9]\d\d|\d\d[1-9]\d|\d\d\d[1-9])$|^(0?2(\/|-)29)(\/|-)(??:0[48]00|[13579][26]00|[2468][048]00)|(?:\d\d)?(?:0[48]|[2468][048]|[13579][26]))$/,
                    "alertText": "* Invalid Date"
                },
                //tls warning:homegrown not fielded 
			"dateTimeFormat": {
                "regex": /^\d{4}[\/\-](0?[1-9]|1[012])[\/\-](0?[1-9]|[12][0-9]|3[01])\s+(1[012]|0?[1-9]){1}:(0?[1-5]|[0-6][0-9]){1}:(0?[0-6]|[0-6][0-9]){1}\s+(am|pm|AM|PM){1}$|^(??:(?:0?[13578]|1[02])(\/|-)31)|(??:0?[1,3-9]|1[0-2])(\/|-)(?:29|30)))(\/|-)(?:[1-9]\d\d\d|\d[1-9]\d\d|\d\d[1-9]\d|\d\d\d[1-9])$|^((1[012]|0?[1-9]){1}\/(0?[1-9]|[12][0-9]|3[01]){1}\/\d{2,4}\s+(1[012]|0?[1-9]){1}:(0?[1-5]|[0-6][0-9]){1}:(0?[0-6]|[0-6][0-9]){1}\s+(am|pm|AM|PM){1})$/,
                    "alertText": "* Invalid Date or Date Format",
                    "alertText2": "Expected Format: ",
                    "alertText3": "mm/dd/yyyy hh:mm:ss AM|PM or ", 
                    "alertText4": "yyyy-mm-dd hh:mm:ss AM|PM"
            }
            };
            
        }
    };

    $.validationEngineLanguage.newLang();
    
})(jQuery);

 

ajaxValidateFieldName.php

 

<?php

/* RECEIVE VALUE */
$validateValue=$_REQUEST['fieldValue'];
$validateId=$_REQUEST['fieldId'];


$validateError= "This username is already taken";
$validateSuccess= "This username is available";



/* RETURN VALUE */
$arrayToJs = array();
$arrayToJs[0] = $validateId;

if($validateValue =="duncan"){		// validate??
$arrayToJs[1] = true;			// RETURN TRUE
echo json_encode($arrayToJs);			// RETURN ARRAY WITH success
}else{
for($x=0;$x<1000000;$x++){
	if($x == 990000){
		$arrayToJs[1] = false;
		echo json_encode($arrayToJs);		// RETURN ARRAY WITH ERROR
	}
}

}

?>

 

ajaxValidateFieldUser.php

 

<?php

/* RECEIVE VALUE */
$validateValue=$_REQUEST['fieldValue'];
$validateId=$_REQUEST['fieldId'];


$validateError= "This username is already taken";
$validateSuccess= "This username is available";



/* RETURN VALUE */
$arrayToJs = array();
$arrayToJs[0] = $validateId;

if($validateValue =="karnius"){		// validate??
$arrayToJs[1] = true;			// RETURN TRUE
echo json_encode($arrayToJs);			// RETURN ARRAY WITH success
}else{
for($x=0;$x<1000000;$x++){
	if($x == 990000){
		$arrayToJs[1] = false;
		echo json_encode($arrayToJs);		// RETURN ARRAY WITH ERROR
	}
}

}

?>

 

What I'm trying to understand is the correlation between the 'validation engine' file and the other two files. In these examples the validation is carried out on the 'User Name' and 'First Name' but would it be possible to actually add the field format criteria to these files i.e. field length etc, rather than having this in the HTML page.

 

My apologies if I've not been particularly clear and fro the lengthy post, but I just wondered whether you may be able to break things down into 'layman's' terms.

 

Many thanks and kind regards

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.