How To Automatically Clean Submitted Forms In Html
Read Time: 9 mins Languages:
A bully way to improve the user experience of your website is to validate and submit forms without a folio refresh.
In this tutorial, I'll show yous how easy information technology is to do just that—validate and submit a contact form without page refresh using jQuery! Let'due south get started.
What We're Edifice
In this example, nosotros have a simple contact form with name, e-mail, and phone number. The grade submits all the fields to a PHP script without whatsoever page refresh, using native jQuery functions.
ane. Build the HTML Form
Let's accept a look at our HTML markup. Nosotros brainstorm with our basic HTML class:
<div id="contact_form"> <form name="contact" activeness=""> <fieldset> <div grade="input-box"> <characterization for="name" id="name_label">Proper noun</label> <input blazon="text" name="name" id="proper noun" minlength="3" placeholder="Monty" class="text-input" required/> </div> <div course="input-box"> <label for="email" id="email_label">Email</label> <input type="e-mail" proper name="email" id="electronic mail" placeholder="example@tutsplus.com" class="text-input"/> </div> <div form="input-box"> <label for="telephone" id="phone_label">Telephone</label> <input blazon="tel" name="phone" id="telephone" grade="text-input" placeholder="856-261-9988"/> </div> <input type="submit" proper name="submit" class="push" id="submit_btn" value="Ship" /> </fieldset> </form> <div course="greetings"> <h1>Contact US</h1> <p>We are waiting to hear from you!</p> </div> </div>
You might find that I have included adiv with idcontact_form that wraps around the entire form.
Be sure to not miss thatdiv in your ain form every bit we volition exist needing this wrapperdiv after on. You might also notice that I have left both the action and the method parts of the form tag bare. We actually don't demand either of these here, considering jQuery takes intendance of it all later on on.
Another important matter is to be sure to include theid values for each input field. Theid values are what your jQuery script volition be looking for to procedure the form with.
We are also doing some very basic client-side validation using HTML5 attributes likerequired andminlength. Theminlength attribute will brand sure that users supply a name that is at to the lowest degree 3 characters long. Similarly, therequired attribute makes sure that users fill up out all the course values you need.
You can read more most these attributes in our tutorial on validating form inputs using simply HTML5 and Regex.
I've added some CSS styles to produce the following form:
* { box-sizing: edge-box; } body { font-family unit: 'Roboto Slab'; font-size: i.5rem; font-weight: 300; } div#contact_form { width: 800px; display: flex; align-items: stretch; justify-content: space-evenly; border: 2px solid black; padding: 10px; } div.input-box { display: flex; margin: 10px 0; flex-wrap: wrap; } div.input-box characterization { display: inline-block; margin: 10px 10px 10px 0; width: 20%; } div.input-box input { font-size: 1.5rem; edge: 1px solid #ccc; padding: 4px 8px; flex: 1; } input.button { font-size: 1.5rem; background: black; color: white; edge: 1px solid black; margin: 10px; padding: 4px 40px; } h1 { font-size: 5rem; text-transform: upper-case letter; font-family: 'Passion One'; font-weight: 400; letter of the alphabet-spacing: 2px; line-tiptop: 0.8; } div.greetings { text-marshal: center; font-size: 1.2rem; background-color: #d3d3d3; background-image: linear-slope(15deg, transparent 28%, rgba(255, 255, 255, 0.five) 28%); background-size: 50px; } div.input-box input.mistake { border: 2px dashed red; background: #fee; } div.input-box label.fault { colour: red; font-size: 1rem; text-align: right; width: 100%; margin: 10px 0; }
2. Begin Calculation jQuery
The adjacent step in the procedure is to add some jQuery code. I'yard going to assume that you accept downloaded jQuery, uploaded to your server, and are referencing it in your webpage.
Side by side, open upward another new JavaScript file, reference it in your HTML as you would whatever normal JavaScript file, and add the following:
$(office() { // gear up course validation hither }); This function runs equally soon as the HTML document is fix. If you accept done whatever piece of work in jQuery previously, this function is the aforementioned as jQuery's document.ready function. Within, we will set up our validation code.
three. Write Some Grade Validation
We will now write some bones form validation using jQuery. This volition improve upon the validation we have so far. Using a validation library gives us more control over the mistake messages that are shown to users. Information technology as well requires minimal or no changes in the markup of the form.
Starting by loading the jQuery Validation library on your webpage. Now, just add the post-obit code:
$(office () { $("form").validate(); }); Make sure you pass the right selector when calling thevalidate() method. This will validate the grade without requiring yous to write any fault messages in the HTML or the logic to display and hide different fault messages in JavaScript. Try submitting the form without filling in whatsoever values or by knowingly adding incorrect input. The form will brandish a prissy error message like the following image.
Using the validation library also allows you to add conditional validation logic to your forms. For example, y'all will be able to add code that requires a telephone number simply when the email accost has not been provided. I have covered this in more item in the jQuery class validation tutorial.
iv. Procedure Form Submission With the jQuery AJAX Function
At present we get to the middle of the tutorial—submitting our form without page refresh, which sends the course values to a PHP script in the background. Let's take a look at all the code first, and then I will pause it down into more than particular next. Add the following code just beneath the validation snippet we added previously:
$( "course" ).on( "submit", function(east) { var dataString = $(this).serialize(); // alert(dataString); return false; $.ajax({ type: "Post", url: "bin/process.php", information: dataString, success: role () { $("#contact_form").html("<div id='message'></div>"); $("#message") .html("<h2>Contact Class Submitted!</h2>") .suspend("<p>We will exist in touch shortly.</p>") .hide() .fadeIn(1500, part () { $("#message").append( "<img id='checkmark' src='images/bank check.png' />" ); }); } }); e.preventDefault(); }); }); There's a lot going on here! Let's break information technology all down—it's so simple and so easy to employ in one case you understand the procedure.
We first create a cord of values, which are all the class values that we want to pass along to the script that sends the email. This tin exist achieved pretty hands using the congenital-inserialize() method in jQuery. This way yous don't have to worry about getting and concatenating the values of dissimilar valid user inputs yourself.
I've commented out an alert that I sometimes use to be certain I am grabbing the correct values, which yous may find helpful in the process. If you lot uncomment that alert and test your form, assuming everything has gone right so far, y'all should get a message similar to the following:
Now nosotros get to our main AJAX function, the star of today'due south prove. This is where all the action happens, then pay close attention!
$("form").on("submit", function (e) { var dataString = $(this).serialize(); $.ajax({ blazon: "POST", url: "bin/process.php", information: dataString, success: role () { // Display message back to the user here } }); e.preventDefault(); }); Basically, what's going on in the code is this: The.ajax() role processes the values from our string calleddataString with a PHP script calledbin/process. php, using the HTTP POST method type. If our script processed successfully, we can and then brandish a message back to the user, and finallyrender imitation so the folio does non reload. That's it! The entire process is handled correct at that place in these few lines!
In that location are more advanced things yous can practise here, other than giving a success message. For example, you could send your values to a database, process them, so display the results back to the user. So if you lot posted a poll to users, you could process their vote, and then return the voting results, all without any page refresh required.
Permit's summarize what happened in our example, to be sure we take covered everything. We grabbed our grade values with jQuery using theserialize() method, then placed those into a string like this:
var dataString = $(this).serialize();
Then we used jQuery'sajax() function to process the values in thedataString. After that process finishes successfully, we brandish a bulletin dorsum to the user andreturn false so that our page does non refresh:
$.ajax({ type: "Mail service", url: "bin/process.php", data: dataString, success: office() { $('#contact_form').html("<div id='message'></div>"); $('#message').html("<h2>Contact Form Submitted!</h2>") .append("<p>We volition exist in touch soon.</p>") .hide() .fadeIn(1500, office() { $('#bulletin').append("<img id='checkmark' src='images/check.png' />"); }); } }); render imitation; The success office of the script has been filled in with some specific content that can be displayed back to the user. But every bit far as our AJAX functionality goes, that's all there is to it. For more options and settings, be certain to bank check out jQuery'due south documentation on theajax role. The example here is one of the simpler implementations, just even then, it is very powerful, equally you tin can encounter.
5. Display a Message Back to the User
Let's briefly await at the part of the lawmaking that displays our message back to the user, to cease out the tutorial.
Kickoff, we modify the entire contents of the#contact_formdiv (remember I said we would be needing that div) with the post-obit line:
$('#contact_form').html("<div id='message'></div>"); This replaces all the content inside the contact form, using jQuery'southhtml() function. And then instead of a grade, we at present have a newdiv with an id ofmessage. Next, we fill that div with an actual message: anh2 maximContact Course Submitted:
$('#message').html("<h2>Contact Form Submitted!</h2>") We'll add even more content to the bulletin with jQuery'southwardappend() function, and to top everything off, we add together a cool effect by hiding the message div with the jQueryhide() function, and then fade it in with thefadeIn() office:
.append("<p>We will exist in affect presently.</p>") .hide() .fadeIn(1500, function() { $('#bulletin').append("<img id='checkmark' src='images/check.png' />"); }); Then the user ends upwards seeing the following after they submit the form:
Determination
By now, I think y'all will have to agree that it'southward incredibly piece of cake to submit forms without folio refresh using jQuery's powerfulajax() office. Just become the values in your JavaScript file, process them with theajax() function, and returnfalse. You tin can process the values in your PHP script just like you would whatsoever other PHP file, the just departure being that the user does non accept to wait for a page refresh—it all happens silently in the background.
So if you have a contact form on your website, a login form, or fifty-fifty more than advanced forms that procedure values through a database and think the results, you tin exercise it all easily and efficiently with AJAX.
Acquire JavaScript With a Free Course
If you desire to principal JavaScript, exist sure to check out our free course to acquire the complete A-Z of mod JavaScript fundamentals.
In this course, you'll learn all of the essential concepts of the JavaScript language. That's right: all of them! Including the nigh important recent improvements to the language, in JavaScript ES6 (ECMAScript 2015) and JavaScript ES7 (ECMAScript 2016).
You'll showtime with the very fundamentals of the language: variables and datatypes. And so in each lesson you lot'll build cognition, from data structures like arrays and maps to loops, control structures, and functions. Along with the basics of the language, y'all'll also larn some primal built-in APIs for manipulating data, AJAX, and working with the web browser DOM. Finally, you'll become a await at some of the most powerful and widely used web APIs that are supported past all modern browsers.
Did you find this mail useful?
How To Automatically Clean Submitted Forms In Html,
Source: https://code.tutsplus.com/tutorials/submit-a-form-without-page-refresh-using-jquery--net-59
Posted by: hobbsfamenig.blogspot.com

0 Response to "How To Automatically Clean Submitted Forms In Html"
Post a Comment