Remove First Append if It Happened Again in Ajax

Read Time: 9 mins Languages:

A great 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 you how easy it is to exercise merely that—validate and submit a contact form without page refresh using jQuery! Let'southward get started.

What We're Edifice

In this example, we accept a simple contact class with proper name, email, and phone number. The grade submits all the fields to a PHP script without whatever folio refresh, using native jQuery functions.

ane. Build the HTML Form

Let's have a await at our HTML markup. We begin with our basic HTML form:

You might notice that I accept included adiv with idcontact_form that wraps around the entire form.

Be sure to non miss thatdiv in your own form every bit 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 demand either of these hither, because jQuery takes intendance of information technology all later on.

Another important thing is to exist sure to include theid values for each input field. Theid values are what your jQuery script will be looking for to process the grade with.

Nosotros are also doing some very basic client-side validation using HTML5 attributes likerequired andminlength. Theminlength attribute will make sure that users supply a name that is at to the lowest degree three characters long. Similarly, therequired attribute makes certain that users fill out all the course values you demand.

You lot tin read more about these attributes in our tutorial on validating class inputs using only HTML5 and Regex.

I've added some CSS styles to produce the following form:

Contact Form Contact Form Contact Form

2. Begin Adding jQuery

The next footstep in the process is to add some jQuery code. I'm going to assume that y'all have downloaded jQuery, uploaded to your server, and are referencing it in your webpage.

Next, open upwards another new JavaScript file, reference it in your HTML as you would whatever normal JavaScript file, and add the post-obit:

This function runs as soon equally the HTML document is ready. If you have done any work in jQuery previously, this function is the same as jQuery's certificate.prepare function. Within, nosotros will set up our validation code.

3. Write Some Form Validation

We will now write some basic form validation using jQuery. This will meliorate upon the validation nosotros have so far. Using a validation library gives u.s. more control over the error messages that are shown to users. It also requires minimal or no changes in the markup of the class.

Starting by loading the jQuery Validation library on your webpage. At present, simply add the post-obit code:

Make sure yous pass the correct selector when calling thevalidate() method. This will validate the form without requiring you to write any fault messages in the HTML or the logic to display and hide dissimilar error messages in JavaScript. Try submitting the grade without filling in any values or past knowingly adding wrong input. The form will display a nice error message like the following image.

Form Validation Error Message Form Validation Error Message Form Validation Error Message

Using the validation library also allows you to add conditional validation logic to your forms. For instance, y'all will be able to add code that requires a telephone number but when the e-mail accost has non been provided. I have covered this in more detail in the jQuery grade validation tutorial.

four. Process Form Submission With the jQuery AJAX Role

At present nosotros get to the heart of the tutorial—submitting our form without page refresh, which sends the form values to a PHP script in the background. Let's have a look at all the lawmaking start, and then I will suspension it down into more detail next. Add the following code just below the validation snippet we added previously:

There's a lot going on hither! Let'southward break information technology all downwardly—it's and then elementary and and so easy to utilise one time you understand the process.

We first create a string of values, which are all the form values that we want to laissez passer along to the script that sends the email. This tin can exist achieved pretty hands using the congenital-inserialize() method in jQuery. This way you don't take to worry virtually getting and concatenating the values of different valid user inputs yourself.

I've commented out an alert that I sometimes utilise to be certain I am grabbing the right values, which you may detect helpful in the procedure. If you uncomment that alert and test your form, bold everything has gone correct and so far, you should get a message like to the following:

Datastirng Alert Datastirng Alert Datastirng Alert

At present we get to our chief AJAX office, the star of today's bear witness. This is where all the action happens, so pay close attention!

Basically, what's going on in the code is this: The.ajax() function processes the values from our string chosendataString with a PHP script calledbin/process. php, using the HTTP Postal service method type. If our script processed successfully, we can then display a bulletin back to the user, and finallyreturn false and then the page does not reload. That's it! The unabridged process is handled right in that location in these few lines!

There are more advanced things you lot can practise here, other than giving a success message. For example, you could send your values to a database, process them, and then display the results dorsum to the user. Then if you posted a poll to users, you could process their vote, and and so render the voting results, all without whatsoever folio refresh required.

Let's summarize what happened in our example, to be sure nosotros take covered everything. We grabbed our class values with jQuery using theserialize() method, and so placed those into a string similar this:

And then we used jQuery'southajax() function to process the values in thedataString. After that process finishes successfully, nosotros display a message back to the user andreturn faux then that our folio does not refresh:

The success part of the script has been filled in with some specific content that tin can be displayed back to the user. Just as far as our AJAX functionality goes, that'southward all there is to it. For more than options and settings, exist sure to check out jQuery'southward documentation on theajax function. The example here is one of the simpler implementations, just yet, information technology is very powerful, every bit yous can encounter.

5. Display a Message Back to the User

Allow's briefly look at the part of the code that displays our message back to the user, to finish out the tutorial.

First, we alter the entire contents of the#contact_formdiv (call up I said we would be needing that div) with the following line:

This replaces all the content within the contact class, using jQuery'due southhtml() function. And then instead of a form, we at present have a newdiv with an id ofbulletin. Next, nosotros fill up that div with an actual message: anh2 maximContact Course Submitted:

We'll add fifty-fifty more than content to the message with jQuery'southwardsuspend() office, and to top everything off, we add a absurd upshot past hiding the bulletin div with the jQueryhibernate() function, and then fade it in with thefadeIn() function:

So the user ends upwardly seeing the following later on they submit the grade:

Successful Submission Successful Submission Successful Submission

Conclusion

By at present, I think you volition have to agree that it's incredibly like shooting fish in a barrel to submit forms without folio refresh using jQuery's powerfulajax() function. Just get the values in your JavaScript file, process them with theajax() function, and returnfalse. You tin can process the values in your PHP script merely similar y'all would any other PHP file, the only difference being that the user does non accept to wait for a page refresh—it all happens silently in the background.

And so if you lot accept a contact form on your website, a login form, or even more than advanced forms that process values through a database and recall the results, you can do it all easily and efficiently with AJAX.

Acquire JavaScript With a Free Course

If y'all want to master JavaScript, exist sure to check out our free form to learn the complete A-Z of modern JavaScript fundamentals.

In this form, you'll learn all of the essential concepts of the JavaScript language. That'due south correct: all of them! Including the virtually important recent improvements to the linguistic communication, in JavaScript ES6 (ECMAScript 2015) and JavaScript ES7 (ECMAScript 2016).

You'll start with the very fundamentals of the language: variables and datatypes. Then in each lesson y'all'll build noesis, from information structures like arrays and maps to loops, control structures, and functions. Along with the basics of the language, yous'll as well learn some primal born APIs for manipulating data, AJAX, and working with the web browser DOM. Finally, you'll get a wait at some of the well-nigh powerful and widely used web APIs that are supported by all modern browsers.

Did you find this mail useful?

fullerthoted.blogspot.com

Source: https://code.tutsplus.com/tutorials/submit-a-form-without-page-refresh-using-jquery--net-59

0 Response to "Remove First Append if It Happened Again in Ajax"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel