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

Using event-driven AJAX

From: JavaScript and AJAX

Video: Using event-driven AJAX

You can use AJAX to update items on a page as a result of some type of event. Events in JavaScript can happen as a result of a user action, like a click or a mouse over an element, and some are triggered by other events, like when something has finished loading or when a key is released. You can use JavaScript to capture the event when it happens and trigger a series of commands. So first, we're going to clean up our HTML a little bit. We'll take out this AJAX page h1. It's not really doing very much. So let me go ahead and save that. And then I'm going to take my script and wrap it inside a function.

Using event-driven AJAX

You can use AJAX to update items on a page as a result of some type of event. Events in JavaScript can happen as a result of a user action, like a click or a mouse over an element, and some are triggered by other events, like when something has finished loading or when a key is released. You can use JavaScript to capture the event when it happens and trigger a series of commands. So first, we're going to clean up our HTML a little bit. We'll take out this AJAX page h1. It's not really doing very much. So let me go ahead and save that. And then I'm going to take my script and wrap it inside a function.

So right now this script is executing whenever it gets to it in the index.html file, which is at the very end. So this page loads and then the script runs right here, so all this is executing right then. So what we'll do is prevent that from happening, by putting everything inside a function. So we'll grab all those code and we'll paste it right there. Let me go ahead and indent that a little bit. And now if I save this and I take a look at my page, you'll notice that nothing is happening because that function is not being called.

So one of the ways that we can call a function is by creating a trigger. So I'm going to add a button here and I'll call this button Load, and I'm going to do an onclick event here, and it looks just like an attribute. And then I'll put LoadAJAX, which will call the function we created in JavaScript. So let me save that and I'll switch over to the browser, refresh the page. We see the Load button, and when we click on it, it should load the text from our file. Of course there's more events that you can use. For example, you can see if somebody has placed the mouse over the button. So we can do that with a different kind of event here; sometimes these are called event handlers.

So we can do an onmouseover, and I'll save that, refresh our page. Now when I go over this button, it loads the text. So mouse over that button and there's the text. So something interesting about events is that not all elements on a page can trigger the same types of events. So for example, there's an element called onload, so you might be tempted to say something like this: whenever this button finishes loading, then execute the function. So let me save that and see what happens. When I refresh the page, this is not loading, and it really doesn't matter what we do here.

That's because the onload event doesn't make sense for buttons; it really only makes sense for a page or a body tag. So it's an attribute that can only go in the body tag. So let me save that and come over here. I'll refresh the page, and now you can see that it's kind of doing what it did before. As soon as the page loads, or as soon as the body of the page has finished loading--and it's going to load the text from our file. That's just one thing to keep in mind, not all elements can trigger any type of event. There's actually a ton of events.

This is a really good place to find out about all the different events: when they happen and what triggers them. So events can be triggered either as attributes, like we have done right here, and they can also be triggered directly through JavaScript. So I'm going to take out the onload handler here and I'm going to save this. If I want to trigger this with JavaScript, I'm going to add an ID to my button so I can easily get to it. So I'm going to save this and I'll switch over to the JavaScript file, and what I'm going to do is create a variable that gets to that button using document.getElementById, and the id that I want is the loadbutton that we created in HTML.

So that puts the button in the mybutton variable, and then what I can do is check for a click. So I can say mybutton.onclick= and then I can execute the function called loadAJAX. So I'll save that. And notice the different notation here. I don't need the parentheses in here. So I'll save that, come over here, refresh, Load button, and now when I click on the button, it loads my text. So there's a different way to write this, and it doesn't really matter which way you do it, but you'll see it in both ways on the web.

So one of the things that you can do to shorten this a little bit is actually create the function as a function literal. So I can get rid of all this right here and just say =function and then it will just execute the function as soon as that mouse is clicked. That's okay if this is the only button that's going to load the list of names for us. If you wanted to use a function that was more generic, you might want to keep it the other way. So let me save this and over here refresh, and we click and there's our text. So events are pretty easy to work with.

They can be triggered either through an attribute in the HTML or through an event handler in JavaScript.

Show transcript

This video is part of

Image for JavaScript and AJAX
JavaScript and AJAX

21 video lessons · 19516 viewers

Ray Villalobos
Author

 

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 JavaScript and AJAX.

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.