Can You Change Css Profile After Submitting
Read Time: 9 mins Languages:
A great style to improve the user experience of your website is to validate and submit forms without a page refresh.
In this tutorial, I'll show you how easy it is to exercise but that—validate and submit a contact form without page refresh using jQuery! Let'south get started.
What We're Building
In this example, we have a simple contact class with name, email, and phone number. The form submits all the fields to a PHP script without any page refresh, using native jQuery functions.
1. Build the HTML Form
Let's take a expect at our HTML markup. We brainstorm with our bones HTML class:
<div id="contact_form"> <form name="contact" action=""> <fieldset> <div class="input-box"> <label for="name" id="name_label">Proper name</label> <input type="text" name="name" id="name" minlength="3" placeholder="Monty" class="text-input" required/> </div> <div grade="input-box"> <characterization for="email" id="email_label">Email</label> <input type="email" proper name="email" id="electronic mail" placeholder="example@tutsplus.com" grade="text-input"/> </div> <div form="input-box"> <label for="phone" id="phone_label">Phone</label> <input type="tel" proper noun="phone" id="phone" class="text-input" placeholder="856-261-9988"/> </div> <input type="submit" name="submit" class="push" id="submit_btn" value="Send" /> </fieldset> </form> <div class="greetings"> <h1>Contact U.s.</h1> <p>We are waiting to hear from you!</p> </div> </div>
You might notice that I have included adiv
with idcontact_form
that wraps around the entire course.
Be sure to not miss thatdiv
in your own course as we will be needing this wrapperdiv
later on. You might also notice that I have left both the action and the method parts of the form tag blank. We actually don't need either of these here, because jQuery takes intendance of information technology all later on.
Another important thing is to be sure to include theid
values for each input field. Theid
values are what your jQuery script will be looking for to process the form with.
We are as well doing some very basic client-side validation using HTML5 attributes likerequired
andminlength
. Theminlength
attribute will make certain that users supply a name that is at least 3 characters long. Similarly, therequired
attribute makes certain that users fill out all the form values you need.
You can read more about these attributes in our tutorial on validating grade inputs using only HTML5 and Regex.
I've added some CSS styles to produce the following grade:
* { box-sizing: border-box; } body { font-family: 'Roboto Slab'; font-size: 1.5rem; font-weight: 300; } div#contact_form { width: 800px; display: flex; marshal-items: stretch; justify-content: infinite-evenly; edge: 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: twenty%; } div.input-box input { font-size: 1.5rem; border: 1px solid #ccc; padding: 4px 8px; flex: ane; } input.push button { font-size: 1.5rem; background: black; color: white; border: 1px solid black; margin: 10px; padding: 4px 40px; } h1 { font-size: 5rem; text-transform: uppercase; font-family: 'Passion Ane'; font-weight: 400; letter-spacing: 2px; line-height: 0.8; } div.greetings { text-align: center; font-size: ane.2rem; background-color: #d3d3d3; background-image: linear-gradient(15deg, transparent 28%, rgba(255, 255, 255, 0.5) 28%); groundwork-size: 50px; } div.input-box input.fault { border: 2px dashed red; background: #fee; } div.input-box label.error { color: red; font-size: 1rem; text-align: correct; width: 100%; margin: 10px 0; }
2. Begin Adding jQuery
The next step in the process is to add some jQuery lawmaking. I'm going to presume that you have downloaded jQuery, uploaded to your server, and are referencing it in your webpage.
Adjacent, open up another new JavaScript file, reference it in your HTML every bit y'all would whatsoever normal JavaScript file, and add together the following:
$(function() { // set up up form validation hither });
This function runs every bit before long every bit the HTML document is gear up. If y'all have washed whatever work in jQuery previously, this function is the same as jQuery'south document.gear up function. Inside, we will fix our validation code.
iii. Write Some Grade Validation
We will now write some basic form validation using jQuery. This will meliorate upon the validation we have so far. Using a validation library gives usa more control over the fault messages that are shown to users. It also requires minimal or no changes in the markup of the grade.
Starting by loading the jQuery Validation library on your webpage. Now, just add the following lawmaking:
$(office () { $("form").validate(); });
Make certain you laissez passer the correct selector when calling thevalidate()
method. This will validate the form without requiring you to write any error messages in the HTML or the logic to display and hide different error messages in JavaScript. Try submitting the form without filling in any values or by knowingly adding incorrect input. The form volition display a nice error message like the post-obit paradigm.
Using the validation library also allows you to add conditional validation logic to your forms. For example, you will be able to add code that requires a phone number only when the e-mail address has not been provided. I have covered this in more detail in the jQuery form validation tutorial.
4. Process Class Submission With the jQuery AJAX Function
Now we become to the centre of the tutorial—submitting our form without page refresh, which sends the form values to a PHP script in the background. Allow's take a await at all the lawmaking first, and then I will break it down into more particular next. Add the following code just beneath the validation snippet we added previously:
$( "form" ).on( "submit", function(due east) { var dataString = $(this).serialize(); // alarm(dataString); render false; $.ajax({ blazon: "POST", url: "bin/procedure.php", data: dataString, success: function () { $("#contact_form").html("<div id='bulletin'></div>"); $("#message") .html("<h2>Contact Class Submitted!</h2>") .append("<p>We will be in touch shortly.</p>") .hide() .fadeIn(1500, function () { $("#message").append( "<img id='checkmark' src='images/check.png' />" ); }); } }); east.preventDefault(); }); });
There'due south a lot going on here! Let'due south break it all down—information technology's then simple then easy to apply once yous understand the process.
We offset create a string of values, which are all the form values that we want to pass along to the script that sends the email. This can be achieved pretty easily using the congenital-inserialize()
method in jQuery. This way you don't have to worry about getting and concatenating the values of different valid user inputs yourself.
I've commented out an warning that I sometimes use to be certain I am grabbing the right values, which you may find helpful in the process. If y'all uncomment that alert and test your form, assuming everything has gone right so far, you should get a message like to the following:
Now we get to our main AJAX part, the star of today'south show. This is where all the activity happens, so pay close attention!
$("form").on("submit", function (east) { var dataString = $(this).serialize(); $.ajax({ type: "Mail service", url: "bin/process.php", data: dataString, success: office () { // Display message dorsum to the user here } }); e.preventDefault(); });
Basically, what'southward 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 candy successfully, we tin can and then brandish a message back to the user, and finallyrender faux
so the page does non reload. That'due south it! The entire process is handled correct there in these few lines!
There are more advanced things you can do here, other than giving a success bulletin. For example, you lot could send your values to a database, process them, and then display the results back to the user. So if you posted a poll to users, you could process their vote, and then return the voting results, all without any page refresh required.
Allow's summarize what happened in our example, to be sure we take covered everything. Nosotros grabbed our form values with jQuery using theserialize()
method, and and so placed those into a string like this:
var dataString = $(this).serialize();
Then nosotros used jQuery'southwardajax()
role to procedure the values in thedataString
. After that procedure finishes successfully, nosotros display a message back to the user andrender simulated
so that our page does not refresh:
$.ajax({ type: "Mail service", url: "bin/process.php", data: dataString, success: office() { $('#contact_form').html("<div id='bulletin'></div>"); $('#message').html("<h2>Contact Form Submitted!</h2>") .append("<p>We will exist in bear upon soon.</p>") .hide() .fadeIn(1500, office() { $('#message').append("<img id='checkmark' src='images/check.png' />"); }); } }); return false;
The success part of the script has been filled in with some specific content that can be displayed back to the user. But as far equally our AJAX functionality goes, that's all at that place is to information technology. For more options and settings, be sure to check out jQuery's documentation on theajax
function. The example hither is one of the simpler implementations, but even so, it is very powerful, as you lot tin can see.
5. Display a Message Back to the User
Let'southward briefly look at the part of the code that displays our bulletin back to the user, to finish out the tutorial.
First, we change the entire contents of the#contact_form
div
(recall I said we would exist needing that div
) with the post-obit line:
$('#contact_form').html("<div id='bulletin'></div>");
This replaces all the content inside the contact form, using jQuery'shtml()
office. So instead of a form, we now have a newdiv
with an id
ofmessage
. Adjacent, we fill that div with an bodily message: anh2
sayingContact Form Submitted:
$('#message').html("<h2>Contact Form Submitted!</h2>")
We'll add even more content to the bulletin with jQuery'ssuspend()
part, and to tiptop everything off, we add a cool effect past hiding the message div with the jQueryhide()
function, and so fade information technology in with thefadeIn()
role:
.append("<p>Nosotros will be in touch soon.</p>") .hibernate() .fadeIn(1500, function() { $('#message').append("<img id='checkmark' src='images/check.png' />"); });
So the user ends upwards seeing the following after they submit the form:
Decision
Past now, I recall y'all will have to agree that information technology's incredibly easy to submit forms without page refresh using jQuery'south powerfulajax()
function. Simply get the values in your JavaScript file, process them with theajax()
function, and returnfalse
. You tin procedure the values in your PHP script just similar you would any other PHP file, the only difference beingness that the user does not accept to wait for a page refresh—it all happens silently in the groundwork.
And so if y'all have a contact form on your website, a login course, or even more advanced forms that process values through a database and think the results, y'all can do it all hands and efficiently with AJAX.
Acquire JavaScript With a Free Course
If you desire to master JavaScript, be sure to check out our free course to learn the complete A-Z of modernistic JavaScript fundamentals.
In this course, yous'll acquire all of the essential concepts of the JavaScript language. That'southward right: all of them! Including the almost important recent improvements to the language, in JavaScript ES6 (ECMAScript 2015) and JavaScript ES7 (ECMAScript 2016).
You'll start with the very fundamentals of the language: variables and datatypes. And then in each lesson you'll build knowledge, from data structures like arrays and maps to loops, control structures, and functions. Along with the basics of the linguistic communication, yous'll as well learn some key built-in APIs for manipulating data, AJAX, and working with the web browser DOM. Finally, you lot'll get a look at some of the most powerful and widely used web APIs that are supported by all modernistic browsers.
Did you notice this postal service useful?
Source: https://code.tutsplus.com/tutorials/submit-a-form-without-page-refresh-using-jquery--net-59
Posted by: thorntonhishad.blogspot.com
0 Response to "Can You Change Css Profile After Submitting"
Post a Comment