jQuery Fade Out Message after Form Submit

In this, tutorial we will see about how to code a message that fades out using jQuery. After jQuery AJAX form submits, we have to respond the user with a fade-in fade-out message. We have already seen the jQuery fading effects on the mouse over event of HTML image elements.

We have an example with an HTML form containing two required fields. The AJAX code validates the form and sends its inputs to PHP. The PHP script responds the AJAX script with a success message. This message will be fade in/out using jQuery.

View Demo

jquery-fadeout-message-after-form-submit

HTML Code for jQuery AJAX Form

This code is to show an AJAX form containing name and comment fields. These two values should not be empty and it is validated using jQuery.

<form id="frmDemo" method="post">
   <div class="input-group">Name </div>
   <div>
        <input type="text" name="name" id="name" class="input-control" />
   </div>
    
   <div class="input-group">Message </div>
   <div>
		<textarea name="comment" id="comment" class="input-control"></textarea>
   </div>

   <div style="float:left">
        <button type="submit" name="btn-submit" id="btn-submit">Submit</button>
    </div>
	<div id="error_message" class="ajax_response" style="float:left"></div>
	<div id="success_message" class="ajax_response" style="float:left"></div>
</form>	

jQuery Fade Out Message on Form Submit

We have a script to submit the HTML form via jQuery AJAX. This script prevents form’s default submit action and call AJAX to get input from form fields. These inputs will be validated and passed to the server side.

If the server-side PHP file receives these inputs, then a success response will be fade in. And then, this response text will be fade out after some time by using Javascript setTimeOut(). We are using jQuery fading methods for showing AJAX response with fade-in fade-out effect. And the code is,

<script>
$("#frmDemo").submit(function(e) {
	e.preventDefault();
	var name = $("#name").val();
	var comment = $("#comment").val();
	
	if(name == "" || comment == "" ) {
		$("#error_message").show().html("All Fields are Required");
	} else {
		$("#error_message").html("").hide();
		$.ajax({
			type: "POST",
			url: "post-form.php",
			data: "name="+name+"&comment="+comment,
			success: function(data){
				$('#success_message').fadeIn().html(data);
				setTimeout(function() {
					$('#success_message').fadeOut("slow");
				}, 2000 );

			}
		});
	}
})
</script>	

View DemoDownload

This jQuery code tutorial was published on April 17, 2016.

↑ Back to Top