Our website will be down for scheduled maintenance on Thursday, September 18, at 11 p.m. Pacific Time and should be back up by Midnight. We apologize for any inconvenience.

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

Using a synchronous XHR request

From: JavaScript and AJAX

Video: Using a synchronous XHR request

The first step in working with AJAX is to learn about the API browsers provide for sending and retrieving information. The way you access the API is by using a XML HTTP request or XHR object. So let's take a look. I'm going to start off with a super-basic page, and it's actually not going to be much of a page; the only thing this page will do right now is to load a separate script file that's going to do all of the work. So I'm going to go ahead and add the script tag right here. It's going to reference a file called script.js. And I don't need this type =text/ javascript, so I'll take it out.

Using a synchronous XHR request

The first step in working with AJAX is to learn about the API browsers provide for sending and retrieving information. The way you access the API is by using a XML HTTP request or XHR object. So let's take a look. I'm going to start off with a super-basic page, and it's actually not going to be much of a page; the only thing this page will do right now is to load a separate script file that's going to do all of the work. So I'm going to go ahead and add the script tag right here. It's going to reference a file called script.js. And I don't need this type =text/ javascript, so I'll take it out.

And I'm going to save this, and I'll go ahead and create the separate file. I have Transmit open right here, so I'll right-click and select New File and I'll call it script.js. I'm also going to need another file called data.txt, so I'll create it by right-clicking again, selecting New File, and calling this data.txt. Now, I'm going to open up data.txt. This file is just going to have the words "Hello World" here. I'll save it, close this out, and I'm going to open up my script.js file.

I don't really need to do anything with the index.html anymore. I'll go ahead and open this up. And just to make a little bit easier to work with, I'll drag it right next to this index tab and so it will doc it at the same place as this window. So let's start by creating the simplest of XHR requests. We'll need to create a new variable for the object that we're creating. Next, we need to create the request to our XHR object. The open function of this object is going to require three parameters.

First, the method, which is going to be either GET or POST. Then the location of the data file. Since it's in the same folder as this document, it will just be the name of the file. I should note here that AJAX requests have what's called a same domain policy, so you cannot request data objects from domains other than the one you're currently on. Now, the last parameter we pass is a Boolean that specifies whether we want the request to be asynchronous or not. To keep things simple, we're making that false, and that makes a request a synchronous request.

This makes our browser wait until the request is done before it does anything else, and this is generally a bad idea, but this is going to make our code simpler for now. So we've created this request, but it hasn't gone to the server yet. The send command is going to take care of that. Now, I'm also going to output the results of the request to the JavaScript console. So I'm going to go ahead and save this and take a look at what we get from the server. So I'll load this page up on the server, and right now the page doesn't do anything.

What I want to do is right-click. I'm in Chrome right now, so I want to select Inspect Element, and this will take me to the Developer Tools. And then I want to hit on this tab that says Console. So when you click on that tab you'll see that it returned an XMLHttpRequest object. And we can open that up and take a look at what's returned from our request to the server. So one of the important things that we see here is the status of the request. That property gives us a number, which in this case says 200. That means the AJAX call was successful.

If any other number was here, like 404 or 500, that would mean the call to the server was unsuccessful. So we can modify our code to check for that property. So I'll save that and then I'll switch over to Chrome, refresh the page, and you'll see we get the same request. Now, you can see that text from the file that was loaded in the response and responseText properties. The responseText property is what you want to use because it always has just the text of our response.

So let's go ahead and output that to our document with the writeln command. So let's save that, and we'll switch back into Chrome, and now we can see the text Hello World appear in our browser. So I mentioned before that these requests we're making are synchronous and that means the server is waiting until the requests are done before it continues. Right now you really can't see that as a problem, because we're only making a single request. So I'm going to change the code and make 100 requests to the server to see what would happen.

So I'm going to save this, and I'll switch over to my browser, and I'll reload the page, and you'll see all the requests being made because I have the console open right now. You can see that there's nothing appearing in my browser until it finishes with all the requests. If you take a look at the Network tab in the Developer Tools in Chrome, you can actually see that the browser is executing the requests in sequence and that the page is not even updating until the whole thing is done, and that's not necessarily a good thing.

So use the XMLhttpRequest object to make calls and request data from your server. You start by opening a connection and then sending the data. You can check the status of your requests, as well as access the text returned by your request and do something with that, like writing it to your page.

Show transcript

This video is part of

Image for JavaScript and AJAX
JavaScript and AJAX

21 video lessons · 19496 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.