Keep value of input fields when form fails to send

Hello all,

I have a pretty basic form that uses php to send an email and do some basic validation. It’s also using ajax so the page doesn’t have to reload on submission. The form’s been working well, but if someone submits the form and it fails validation, all form fields are reset.

How would I go about keeping the values a user has entered when the form fails? I have a feeling it’ll have something to do with my javascript file, but I’m a newb with javascript and not really sure what direction to go. Can anyone help?

here’s my form.html:

<form method="post" action="" enctype="multipart/form-data" id="contact">
  	<div id="response"></div>
  	<div class="form-group">
    	<label for="name">Your Name:</label>
      <input type="text" name="name" id="name" class="form-control" placeholder="Jesse James">
    </div>
    <div class="form-group">
    	<label for="email">Email:</label>
      <input type="email" name="email" id="email" class="form-control" placeholder="howCan@weReachYou.com">
    </div>
    <div class="form-group">
    	<label for="phone">Phone:</label>
      <input type="tel" name="phone" id="phone" class="form-control" placeholder="734-968-4509">
    </div>
    <div class="form-group">
    	<label for="message">Message</label>
    	<textarea class="form-control" id="message" name="message" rows="6" placeholder="How can we help...?"></textarea>
    </div>
  	<button type="submit" name="submit" id="submit" class="btn btn-default">Send It</button>
    <input type="hidden" name="honeypot" id="honeypot" value="http://">            
    <input type="hidden" name="humancheck" id="humanCheck" class="clear" value="">
  </form>
<script src="js/ajax_submit.js"></script>

The ajax_submit:

$(document).ready(function() {

	$('#contact input:submit').click(function() {
		$('#contact form').attr('action', 'http://' + document.domain + '/php/feedback.php');
		$('#contact form').submit();
	});

	$('form #response').hide();
	$('form #nameResponse').hide();
	$('form #phoneResponse').hide();
	$('form #emailResponse').hide();
	$('form #messageResponse').hide();
	$('#submit').click(function(e) {

		// prevent forms default action until
		// error check has been performed
		e.preventDefault();

		// grab form field values
		var valid = '';
		var nameResponse = '';
		var phoneReponse = '';
		var emailResponse = '';
		var messageResponse = '';
		var required = ' is required.';
		var name = $('form #name').val();
		var phone = $('form #phone').val();
		var email = $('form #email').val();
		var message = $('form #message').val();
		var honeypot = $('form #honeypot').val();
		var humanCheck = $('form #humanCheck').val();

		// perform error checking
		if (name = '' || name.length <= 2) {

			nameResponse = '<p>Your name' + required +'</p>';	

		}
		
		if (phone ) {
			
		}
		
		if (!email.match(/^([a-z0-9._-]+@[a-z0-9._-]+\.[a-z]{2,4}$)/i)) {

			emailResponse += '<p>Your email' + required +'</p>';												  

		}

		if (message = '' || message.length <= 5) {

			messageResponse += '<p>A message' + required + '</p>';	

		}	

		if (honeypot != 'http://') {

			valid += '<p>Spambots are not allowed.</p>';	

		}

		if (humanCheck != '') {

			valid += '<p>A human user' + required + '</p>';	

		}

	// let the user know if there are erros with the form

		if (valid != '') {
			

			$('form #response').removeClass().addClass('error')
				.html('<div class="alert alert-danger">'+
					'<strong>Please correct the errors below.</strong>' + '</div>'
							).fadeIn('fast');
							
			if (nameResponse != '') {
					$('form #nameResponse').removeClass().addClass('error')
						.html('<div class="alert alert-danger">'+
							nameResponse + '</div>'
								).fadeIn('fast');
			}
			
			if (phoneResponse != '') {
					$('form #nameResponse').removeClass().addClass('error')
						.html('<div class="alert alert-danger">'+
							phoneResponse + '</div>'
								).fadeIn('fast');
			}
			
			if (emailResponse != '') {
					$('form #nameResponse').removeClass().addClass('error')
						.html('<div class="alert alert-danger">'+
							emailResponse + '</div>'
								).fadeIn('fast');
			}
			
			if (messageResponse != '') {
					$('form #nameResponse').removeClass().addClass('error')
						.html('<div class="alert alert-danger">'+
							messageResponse + '</div>'
								).fadeIn('fast');
			}

		}
		// let the user know something is happening behind the scenes
		// serialize the form data and send to our ajax function
		else {

			$('form #response').removeClass().addClass('processing').html('Processing...').fadeIn('fast');										

			var formData = $('form').serialize();
	
			submitForm(formData);			

		}

	});
	
});

function submitForm(formData) {
	$.ajax({
		
		type:			'POST',
		url:			'php/feedback.php',
		data:			formData,
		dataType:	'json',
		cache:		false,
		timeout:	7000,
		success:	
		function(data) {
			//we are getting data.error (from ajax, which is formData) and data.msg from our feedback.php
			$('form #response').removeClass().addClass((data.error === true) ? 'error':'success')
										.html(data.msg).fadeIn('fast');
			if ($('form #response').hasClass('success')) {
				setTimeout ("$('form #response').fadeOut('fast')",5000);
			}
		},
		error: 
		function (XMLHttpRequest, textStatus, errorThrown) {
			$('form #response').removeClass().addClass('error')
						.html('<div class="alert alert-danger">' +
							'<p>There was an <strong>' + errorThrown + 
									'</strong> error due to a <strong>' + textStatus +
										'</strong> condition.</p>' +
											'</div>').fadeIn('fast');
		},
		complete: function(XMLHttpRequest, status) {
			$('form') [0].reset();
		}
		
		
		
	});
};

And finally, my feedback.php:

<?php 
sleep(.5);
//Sanitize incoming data and store in variable
$name = trim(stripslashes(htmlspecialchars($_POST['name'])));	  		
$email = trim(stripslashes(htmlspecialchars($_POST['email'])));
$phone = trim(stripslashes(htmlspecialchars($_POST['phone'])));
$phoneLink = preg_replace('/\D+/', '', $phone);
$message = trim(stripslashes(htmlspecialchars($_POST['message'])));	    
$humancheck = $_POST['humancheck'];
$honeypot = $_POST['honeypot'];

if ($honeypot == 'http://' && empty($humancheck)) {	
		
		//Validate data and return success or error message
		$error_message = '';	
		$reg_exp = "/^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9-]+\.[a-zA-Z.]{2,4}$/";
		
		if (!preg_match($reg_exp, $email)) {
				    
					$error_message .= "<p>A valid email address is required.</p>";			   
		}
		if (empty($name)) {
				   
				    $error_message .= "<p>Please provide your name.</p>";			   
		}			
		if (empty($message)) {
					
					$error_message .= "<p>A message is required.</p>";
		}		
		if (!empty($error_message)) {
					$return['error'] = true;
					$return['msg'] = '<div class="alert alert-danger">'."<h3>Oops! The request was successful but your form is not filled out correctly.</h3>".$error_message;					
					echo json_encode($return);
					exit();
		} 
		
		else {
			//mail variables
			#$to =				'Mainstwebguy@gmail.com';
			$to =			'Jason@mainstreetcomp.com';
			$from = $_POST['email'];
			$headers =	'From: '.$from."\r\n";
			$headers .=	'MIME-Version: 1.0' . "\r\n";
			$headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";
			$subject = 	"Contact Form Submission\n";
			

			$body =			'<p>Name:   '.$name."</p>";
			$body	.=		'<p>Email:  '."<a href=\"mailto:".$email.'"'.">".$email."</a>"."</p>";
			if(isset ($phone) && $phone != '') {
				$body .=	'<p>Phone: '.'<a href="tel:+1'.$phoneLink.'"'.$phone.'>'.$phone."</a>";
			}
			
			$body .=		'<p>Message:   '.$message."</p>";
			
			//send email and return a message to user
			if(mail($to, $subject, $body, $headers)) {	
				$return['error'] = false;
				$return['msg'] = 
					'<div class="alert alert-success">'.
						"<h3>Thanks for your feedback " .$name ."</h3>".
						"<p>We'll reply to you at ".$email." as soon as we can.</p>";
						 
						echo json_encode($return);
			}
			else {
				
				$return['error'] = true;
				$return['msg'] = "<h3>Oops! There was a problem sending the email. Please try again.</h3>";	
				echo json_encode($return);
			}

		}
				
} 
else {
	
	$return['error'] = true;
	$return['msg'] = "<h3>Oops! There was a problem with your submission. Please try again.</h3>";	
	echo json_encode($return);
}
	
?>

Give each of your input fields a value. I use just PHP and my inputs include something like

value="<?php if ( isset($name) ) echo $name; ?>"

I guess you’ll want to do something similar in JS.

The problem is here:

complete: function(XMLHttpRequest, status) {
    $('form')[0].reset();
}

The complete callback fires whether the AJAX request is successful or not, and is resetting the form. If you move that line of code into the success function it’ll only reset the form if it was submitted without any errors.

1 Like

Thanks fretburner. Where exactly is that? Not trying to be lazy, i’ve added it to a couple places i thought made sense, but when i do the form breaks. Where should I be adding it?

Really appreciate it :smile:

Oops! I think i found it. I was including the “complete:” on there and that was jacking things up.’

Thanks again!

keep shreddin’

1 Like

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.