Easy-to-follow video tutorials help you learn software, creative, and business skills.Become a member

Processing form data with AJAX

From: Validating and Processing Forms with JavaScript and PHP

Video: Processing form data with AJAX

You probably haven't noticed that when we submit this form, the entire page has to reload. In this form, it happens so fast that you can't really tell. If this were part of a bigger page you would definitely notice the reload. We can have the process for the PHP file do it's work in the background without having to reload the page. That's what AJAX is for. AJAX is a complicated subject by itself, so if you're interested in learning more about AJAX, make sure you check out my other course, JavaScript and AJAX. I'm going to use JQuery's version of AJAX because it's simpler and more backwards compatible.

Processing form data with AJAX

You probably haven't noticed that when we submit this form, the entire page has to reload. In this form, it happens so fast that you can't really tell. If this were part of a bigger page you would definitely notice the reload. We can have the process for the PHP file do it's work in the background without having to reload the page. That's what AJAX is for. AJAX is a complicated subject by itself, so if you're interested in learning more about AJAX, make sure you check out my other course, JavaScript and AJAX. I'm going to use JQuery's version of AJAX because it's simpler and more backwards compatible.

One problem with AJAX and JavaScript is that they weren't designed to allow you to send files. So. if you've been following along with the project, you may notice this version of the exercise document is a little bit different. Its pretty much the one without the file uploading code. In the previous movie we removed the HTML5 validation. I've added the pattern and the required attributes in the main input field. I've also added our script file from the end of our chapter called jQuery form validation. And we a have a call to that script at the bottom of the page. Here's the script. Right now this script is doing two things.

At the very top when somebody submits the form, it checks to see if each required field has been filled. If it doesn't, it outputs an error beneath each input field. The second thing it does, is check for pattern and placeholder attributes when somebody moves away from an input field. We're going to leave the second part alone. We're just interested in the first part. Right now if everything's hunky dory, it sends the script to the process.php file. That happens right here, when it returns true.

We want to interrupt that and handle the sending of the data ourselves using AJAX. So we're going to change this line right here and add our own posting script. We'll add some AJAX code to send the form to the processor. It's not a lot of code. The first thing we need to do is serialize the form data. When data gets sent over by hitting the Submit button, the data gets converted into a format that the processor can understand. JQuery uses the serialize function for that. We'll store that in a variable called postData. You can find more about the serialize function on this page.

Right here, we'll create a variable called postData. We'll assign it to the form with the ID of MyForm, and we'll serialize that data. So all the input fields will be converted into a language that depresses that PHP file will understand. So now we're ready for the AJAX part. JQuery makes it ridiculously simple. It has several methods including an AJAX method. But since we want to use the POST method for this form, there's a shortcut for that called POST. Here's the documentation field for the POST method. So we're going to use the POST method and in here we'll pass it the processing script we want to use to process this file.

That's the process.php file. And then we'll pass it the POST data that we've already serialized. I'm also going to pass along some additional information. I want this form to work if someone has JavaScript turned off. The form is already doing that, but if the form comes from my AJAX code, I want to identify it by passing a special variable that lets my PHP file know this version of the form is coming from JavaScript. So I'll add a plus here and then ampersand AJAX Request equals one.

I also need to send the action variable with the value submit. That's because if somebody doesn't hit that Submit button, the information from that button doesn't get passed along. So we need to kind of fake it, so we'll add another ampersand here, and we'll just pass along a variable action, just like the button equals submit. This is how you pass along additional info to your script. Just encode it like a normal URL. Finally, if I want to do something when the processor is done with the form, then I can just pass it along a function. Now this function will return a message.

I'm going to store it in an MSG variable. Now if that message exists, I want to go ahead and put it before the current form. I'll use the before method and pass it along the message. So whatever gets returned from the process.php file is going to be placed right before the form. I also need to have the form submission event return false, so my form wouldn't ever arrived at the process.php file unless it's going through our JavaScript. All right, so that should be it for our script.

I'm going to save this and then I'm going to switch over to the process.php file. So just like with any other variable that comes in from the form, I'm going to make a copy of this one and add a check for the AJAX request variable. If it exists, we'll create a variable called Ajax Request in the PHP document. And we'll place whatever we got from the AJAX Request in there. This form is working great for our PHP document, but how do we get it to talk back to the JavaScript file? There is a couple of ways of doing that. One way would be by printing anything. The problem is that if we print something, it's going to print even if people don't have JavaScript turned on, and that could ruin our output for those users.

We need it to print out something only if we're calling the form from our script. That's easy enough, we have a special variable we just created called AJAX Request. And we could use that to pass along the FormData adjacent object from this associative array. But I'm going to do something slightly different, I'm going to pass along a series of text strings that will create scripts that do different things on the form. This is a nice way of having your PHP document, talk to a JavaScript document. So these are kind of boring, so I'm going to copy them from a codesnippets.md file and, essentially its checking for the AJAX Request.

If that exists that's going to print out a script just like you would create in JavaScript. That script is going to find the input field, in this case it's finding the password input field, and after that it's going to place some HTML. So only do that for certain fields, HTML5 is already going to take care of any required fields and any pattern fields. So here, I'm just adding them to the password, password confirmation and a thank you for when the form is submitted. So I'm going to copy this first one right here, go back into my process.php file and move up a little bit. I'm not going to worry about this line right here because HTML5 already will take care of this.

But it won't take care of the passwords, so I'm going to add that here. Next I'm going to check for the confirmation. I'll copy this line and I'll paste it right here. Finally if the email is successful I also want to send back a message. I'm going to come over here. I'm going to grab this line. Now most of the time this, if else endif notation that you see right here works really well. And I really like it because it aligns things really well. But in this case, this if notation right here that uses the curly brackets combined with this L statement is not going to work. So, I'm going to modify that and just make em consistent. So, I'll move that like this and instead of this curly bracket here, I'll do an end if and that way these won't get confused.

Now, notice that I'm doing a couple of things here. In this line, I'm printing out a message with this script tag before the current form then over here I hide the form so that it goes away and that's important to know. So I'm going to go save this and switch back to my form and I'll try filling it out. And I'm going to hit the Send button, you'll notice that it gives us a message. Now this looks exactly like the PHP message. How do you know if this form was submitted through JavaScript or PHP. What you could do is, right-click and select Inspect Element.

If you see that the form command is still there, then you know you're doing it with JavaScript. Notice that the display attribute is set to none, which is what's hiding this form. That means that the form is being processed with JavaScript and not with PHP. PHP wouldn't even show the form at all. So working with forms in AJAX is pretty easy. I really like the way that you tell JavaScript to send things to PHP, and PHP to send commands back to JavaScript.

Show transcript

This video is part of

Image for Validating and Processing Forms with JavaScript and PHP
 
Expand all | Collapse all
  1. 3m 36s
    1. Welcome
      1m 9s
    2. What you should know
      1m 2s
    3. Using the exercise files
      1m 25s
  2. 12m 50s
    1. Understanding forms
      2m 2s
    2. Working with form fields
      7m 4s
    3. Using the form tag
      3m 44s
  3. 19m 23s
    1. Using input validation
      2m 10s
    2. Adding required fields and placeholders
      1m 31s
    3. Constraining numeric and date fields
      2m 32s
    4. Accepting multiple entries
      1m 41s
    5. Limiting uploads by MIME types
      2m 35s
    6. Assisting text input with a datalist
      1m 55s
    7. Constraining with regular expression patterns
      6m 59s
  4. 42m 13s
    1. Accessing forms
      3m 57s
    2. Looking up form elements
      3m 35s
    3. Handling focus changes
      2m 47s
    4. Detecting the onchange event
      4m 31s
    5. Using the selectedIndex property
      2m 30s
    6. Dynamic validation with regular expressions
      7m 0s
    7. Creating a generic input validation function
      4m 31s
    8. Validating in older browsers with Modernizr
      7m 32s
    9. Interrupting form submission with onsubmit
      5m 50s
  5. 15m 20s
    1. Understanding jQuery
      3m 47s
    2. Validating on submit with jQuery
      3m 45s
    3. Building interactive jQuery validation
      2m 34s
    4. Using the jQuery Validation plugin
      5m 14s
  6. 32m 57s
    1. Communicating with PHP servers
      2m 27s
    2. Retrieving data from superglobals
      8m 18s
    3. Using server-side validation
      4m 59s
    4. Adding in-page validation
      5m 22s
    5. Mirroring input data back to the user
      7m 46s
    6. Sanitizing form input
      4m 5s
  7. 43m 29s
    1. Mailing form data
      8m 28s
    2. Understanding file uploads
      3m 1s
    3. Uploading files
      9m 20s
    4. Processing form data with AJAX
      8m 14s
    5. Preparing your database
      5m 50s
    6. Pushing data
      8m 36s
  8. 1m 17s
    1. Next steps
      1m 17s

Start learning today

Get unlimited access to all courses for just $25/month.

Become a member
Sometimes @lynda teaches me how to use a program and sometimes Lynda.com changes my life forever. @JosefShutter
@lynda lynda.com is an absolute life saver when it comes to learning todays software. Definitely recommend it! #higherlearning @Michael_Caraway
@lynda The best thing online! Your database of courses is great! To the mark and very helpful. Thanks! @ru22more
Got to create something yesterday I never thought I could do. #thanks @lynda @Ngventurella
I really do love @lynda as a learning platform. Never stop learning and developing, it’s probably our greatest gift as a species! @soundslikedavid
@lynda just subscribed to lynda.com all I can say its brilliant join now trust me @ButchSamurai
@lynda is an awesome resource. The membership is priceless if you take advantage of it. @diabetic_techie
One of the best decision I made this year. Buy a 1yr subscription to @lynda @cybercaptive
guys lynda.com (@lynda) is the best. So far I’ve learned Java, principles of OO programming, and now learning about MS project @lucasmitchell
Signed back up to @lynda dot com. I’ve missed it!! Proper geeking out right now! #timetolearn #geek @JayGodbold
Share a link to this course

What are exercise files?

Exercise files are the same files the author uses in the course. Save time by downloading the author's files instead of setting up your own files, and learn by following along with the instructor.

Can I take this course without the exercise files?

Yes! If you decide you would like the exercise files later, you can upgrade to a premium account any time.

Become a member Download sample files See plans and pricing

Please wait... please wait ...
Upgrade to get access to exercise files.

Exercise files video

How to use exercise files.

Learn by watching, listening, and doing, Exercise files are the same files the author uses in the course, so you can download them and follow along Premium memberships include access to all exercise files in the library.


Exercise files

Exercise files video

How to use exercise files.

For additional information on downloading and using exercise files, watch our instructional video or read the instructions in the FAQ.

This course includes free exercise files, so you can practice while you watch the course. To access all the exercise files in our library, become a Premium Member.

Join now "Already a member? Log in

Are you sure you want to mark all the videos in this course as unwatched?

This will not affect your course history, your reports, or your certificates of completion for this course.


Mark all as unwatched Cancel

Congratulations

You have completed Validating and Processing Forms with JavaScript and PHP.

Return to your organization's learning portal to continue training, or close this page.


OK
Become a member to add this course to a playlist

Join today and get unlimited access to the entire library of video courses—and create as many playlists as you like.

Get started

Already a member?

Become a member to like this course.

Join today and get unlimited access to the entire library of video courses.

Get started

Already a member?

Exercise files

Learn by watching, listening, and doing! Exercise files are the same files the author uses in the course, so you can download them and follow along. Exercise files are available with all Premium memberships. Learn more

Get started

Already a Premium member?

Exercise files video

How to use exercise files.

Ask a question

Thanks for contacting us.
You’ll hear from our Customer Service team within 24 hours.

Please enter the text shown below:

The classic layout automatically defaults to the latest Flash Player.

To choose a different player, hold the cursor over your name at the top right of any lynda.com page and choose Site preferencesfrom the dropdown menu.

Continue to classic layout Stay on new layout
Exercise files

Access exercise files from a button right under the course name.

Mark videos as unwatched

Remove icons showing you already watched videos if you want to start over.

Control your viewing experience

Make the video wide, narrow, full-screen, or pop the player out of the page into its own window.

Interactive transcripts

Click on text in the transcript to jump to that spot in the video. As the video plays, the relevant spot in the transcript will be highlighted.

Are you sure you want to delete this note?

No

Your file was successfully uploaded.

Thanks for signing up.

We’ll send you a confirmation email shortly.


Sign up and receive emails about lynda.com and our online training library:

Here’s our privacy policy with more details about how we handle your information.

Keep up with news, tips, and latest courses with emails from lynda.com.

Sign up and receive emails about lynda.com and our online training library:

Here’s our privacy policy with more details about how we handle your information.

   
submit Lightbox submit clicked
Terms and conditions of use

We've updated our terms and conditions (now called terms of service).Go
Review and accept our updated terms of service.