Tip:
Highlight text to annotate it
X
hello everyone in this episode i would like to spend some time talking about a
javascript uh... technology called ajax.
ajax is kind of all the rage on the web nowadays a lot of times it seemed as
being fairly synonymous uh... with the term web two point o which you hear
people talk about pretty frequently
and what ajax actually is
is really just a uh... one particular... particular little trick that
uh... javascript has uh... up its sleeve
one particular thing that uh... javascript can be used to accomplish.
if you think about the way the web usually works
everything that occurs on a web page tends to be uh... to a certain extent
what we would call synchronous
meaning that when we load a page uh... all of the data that's available in the
javascript and the html at that time
is basically all of the data that the javascript and the html have available. in
order for there to be any additional data or different data available to the
javascript or the html, the page has to be reloaded again.
but with ajax what we actually get
is the ability to do asynchronous javascript calls
this basically means that javascript is able to make requests to the server for
additional data for any kind of information it might happen to need
and is able to do these requests without the page actually being reloaded. ajax
itself a j a x actually stands for asynchronous
oops
javascript
and
xml
so the a synchronous part is basically what i just described to you and the
javascript part of course means that javascript is what's doing things
asynchronously
so javascript is able to asynchronously uh... meaning not at the time that the
page is reloaded
be able to request and gather additional data from the server
which otherwise would not be available to it
uh... the word and of course is just the word and it's really nothing all that
terribly significant
and the last word xml is actually a data format
it's uh... related in a lot of ways to html. xhtml is actually a combination of
xml and html
and basically the reason that the xml is in there
is that when this data is transferred from the server back to the javascript
or... possibly from the javascript to the server
that data has to be sent in some format that will be recognizable to both.
it has to be something the javascript will be able to read and it'll have to
be something that the server is able to understand and produce
so originally when this technique first was developed xml was the language
of choice, the data format of choice. it's a fairly universal data format it was
something that javascript could work with relatively easy
and certainly something that can be produced by a server without any trouble.
but one of the funny things about ajax nowadays is that x ml, while it's still
can be used, we'll find is often not the most convenient data format to use
instead what we'll use a lot of times nowadays is a thing called json which
we've actually talked about before
some people pronounce it jason i call j son don't ask me why
uh... but json is javascript uh...
objects notation - JavaScript Object Notation and what we can do is we can
actually use json in place of the xml.
so it becomes a synchronous javascript and json are page a_ j_a_j or something
like that - ajaj i guess it would be called.
uh... anyway ajax uh... with xml in there certainly sounds like a much nicer
acronym something that's much more pronouncable.
but nevertheless it is something that's important to keep in mind that xml is
not a requirement necessarily to be able to do what they still nowadays called
ajax even if uh... xml isn't being used
uh... ajax is still the term that's typically used to kind of described this
uh...
this technique.
so anyway uh... few quick examples uh... certainly one of the companies that's
biggest into ajax or has been since the beginning has been google.
i would imagine that probably most of you have seen google maps before, and if
you actually think about how google maps works you kind of start to see where ajax
lies in here.
When we pull up google maps it of course has an actual map down here for us at
the bottom which we can of course click and drag around. All fancy javascript
tricks no flash involved here.
But the neat thing about it is that it would be unrealistic for this page to
actually have detailed maps in three or four different forms of the entire world
present in the html javascript at the time the page loads.
If google tried to put all of their detailed maps all of their detailed
images that they use here in their maps application into the html in the java script,
it would probably take this page half an hour or more to actually download.
so what they do is when you first come to this page you're shown sort of a
starting map
but then whenever you move around you'll sometimes notice the map kinda filling
in and changing a little bit as you work your way around it.
you see the effect even more when you zoom in and sometimes you can kind of catch
different blocks of the page reloading.
And what's actually happening is every time we moved the map, every time we
zoom in to a different level of the map the javascript is behind the scenes
calling back to google servers and requesting
that new information be downloaded.
It's using ajax to do that so that all of this can actually happen without
the page actually having to be
uh... refreshed everytime. It all happens a synchronously sort of in the
background you might say
without us ever actually having to hit the refresh button, so
it's a pretty neat thing and can be used for pretty spectacular affect.
what i want to do in this particular example to kind of demonstrate this is
to put our own little ajax tool together
is i have a server running here on my local machine, you'll notice
my address up here,local host port three thousand.
i'm pulling up a page called new user dot html. And what i have here on this
particular page is I have a user registration form.
the user registration form asks for a very generic sort of information like
these things usually do. A users first name and last name, their email address,
their username, and their password.
now basically where I plan on putting ajax in here is that some of these
pieces of data on this page are things that javascript can easily validate
itself.
Things like first name, it can confirm whether a first name is present
or whether the field's blank, same thing for last name.
For email address we can pretty easy ... easily use a regular expression to
determine whether a valid email address has been used.
Then for password
what we're gonna wanna do is simply make sure that password meet our requirements
in this case i said that the password has to be at least eight characters long.
But for something like username there's a few different aspects of validating
this username that we're gonna have to uh... handle. one of them of course is
that the user name cannot be blank, it's a required field,
but the other is that anybody registering for the site needs to pick a
unique username. A username that no other user has used when they were registering.
Now one way to handle this would be to in this page itself either in the
javascript or the xhtml somewhere
we could actually have the server automatically put in every
registered users username
so that our javascript would then have access to it from its own
little data store when it downloaded to a client's computer.
but if we had a lot of users or if we were at all squeamish about letting our
list of usernames get out, which frankly wouldn't be a too terribly good idea,
then that wouldn't be a very practical way to be able to validate this username. So
what we can do instead is we can instead have javascript automatically
make an asynchronous call, an ajax call, back to the server with whatever
username the user fills in.
Then the server can look up that username see if it is taken or not and
and then respond back to the javascript letting it know that yes that username
is available or no that username is already taken.
so that's more or less the field we're gonna be concentrating on as far as
our ajax is concerned.
having it talk to the server and find out what usernames are available and what
user names are not.
the way that i've actually set up the validation for this form is a little bit
different than we've talked about previously.
uh... previously when we talked about uh... form validation we've basically
done it in more or less sort of a synchronous manner where we more or less
let the user fill out the form and then when they hit submit at that point
we determine whether the form appears to be valid or not.
what i've actually done in this example is just a little bit different i've
actually tied into what they call the on blur
event for each one of these fields.
so as soon as i leave the field it immediately validates it . so here you can
see i focused on the first name field as soon as i left
it validated it, saw that it was blank, came back and told me that
you cannot leave this field blank.
if i come back to the first name field and i type in some actual data and leave
it, i have it set up to give me a little green check mark letting me know
at that field is now
complete to the best of javascript ability to be able to check.
So it goes through and it checks all these different things you can see for the
last name it says it can't be blank for the email address it says the email
address is invalid
right now for the username field i just had it pop up an alert box that says check the
name 'cause that's something that we're gonna work on here in this episode.
and down here in the password field it comes back and says that the password
must be at least eight characters long.
if i go through and actually fill in these different fields.
uh... except for the username field since it's obviously notgoing to work right
now,
you can see how it goes through and gives me a green check mark every time a field
is correct, but if i go back to a field
and erase it, it goes back to giving me the error message again.
So I already have all of the validation for all the fields except for username
setup so that's really the only thing that we need to concentrate on.
but before we actually dig into that let's go ahead and take a look at how
i've done the validation that's available so far.
what i essentially have here in my html filed down at the bottom is inside
my form which begins up here on line 105 goes all the way down here to
the bottom of the body is i have uh... all of my different form fields put in.
each one of the form fields, each one of the input field specifically is set up in
a format so that it will be understandable to the server that this is
working with so i can actually submit this data and have it actually generate
new user registration records in a database uh...
uh... what i have is each one of the labels in the fields inside its own
paragraph and all of that is basically already set up
one thing i don't have you'll notice is inside each one of those paragraphs i do
not have an image so that green check mark or the yellow warning sign are
being dynamically added by the javascript
uh... the way i actually did that then
was up in the head section of this document which is fairly long because all the
javascript that's in there already
i have basically in a window dot onload event i sign a function to it so as soon
as this page is loaded
what i do is i go and i get all of the paragraph tags that are inside the
new user element which is the form itself
and uh... i assign that array of paragraph tags here to a uh...
p variable, a variable called p.
the next thing i do then is i have a for loop that's going to go through all
those paragraphs and for what it'll do... what it'll do for each one of them is it
will create an image uh... uh... element and image html element
it will then go and actually retrieve the input tag that's inside that
particular paragraph
and it will then set the images id
so that its id is the same as the input fields id exceptit will have underscore
image assigned to the end of it. here then i actually go and i append the image to
the paragraph so i end up with the image tag there at the end of every
paragraph so it's ready to go
to actually accept uh... whatever image it choose to assign to it.
initiall i don't put an image into it at all i wait until we're actually doing our
validation before i put any images in.
the next thing i do then
is as we go through this for loop and we check each one of our paragraphs
i use a regular expression here to actually look at the i_d_ for that
paragraph or... i'm sorry... for that input field so in this case what i'm saying is
that if the input field has the string name n-a-m-e somewhere as part of its line,
as it's id
then i'm going to assign to it on blur
even,t a function that i've written called checkmate which is down below
here, I'll show it to you here in a second.
if the id of the input tag has email in it then I assign my check
email function;
if the i_d_ of the input field has user name in it then i assign my check
username function; and if it's a password i assign my check password function.
so more or less i have it sort of generically going through and based on
the actual ids of the input fields guessing what type of field that is
and then assigning the appropriate type of validation to its on blur
event.
now my actual functions that will go through and do the validation are fairly
simple for the most part. at the moment the check name for example which more or
less is just making sure the field isn't blank
takes the actual field itself.
since the check name function in this case is part of the on blur event for the
input field
inside that function whenever
we refer to this, we're referring to the field itself.
so here i am saying if the value of this field's length is greater than zero
then that means everything is okay.
when everything is okay i have another function that I've written called show valid which
i passed this element to so basically i'm passing the input tied to it.
whenever we have a field that isn't valid for example up here if the length of
the value of the name fields are not greater than zero
then i call show invalid i pass it the input field along with the message that
i wanted to display "you cannot leave this field blank."
i do more or less the same thing for all of the validation that i really have in
here for check email i do the exact same thing except other than just looking for
blank have this big long gnarly looking regular expression which looks for a
valid... validly formatted email address
if the email address is valid then it shows it as being valid otherwise it
shows it as being invalid and says the email address does not appear to be valid.
like i mentioned before for check username right now all i have in there
is an alert, this is where we're going to be doing most all of our work
for check password i have a check for any character
repeating eight times
as long as it has that it's valid, otherwise they get this error message
that goes along with that field.
what i then have is the actual show valid and show invalid functions along
with one additional one that i figured we would need when we did our ajax called
show waiting.
whenever i mark a field as being valid what i do is i simply take the input
tag
i go to its parent node which is the
paragraph
and from that paragraph i ask it to give me all of the image tags inside
that paragraph
now get elements by tag name of course returns an array but i know that there's
only one image in each one of them so as soon as that array has returned i
immediately just take the zeroth element
and i end up with the image tag stored there
now that i think about it i probably could have simplified that a little bit since i
gave the image an id, i could have just then get on that i_d_ based on
the id of the input field but
uh... what the...what the hey this is
probably gonna work out just fine.
anyway once the actual image is uh... is uh... retrieved what i do next is i
assign to the source of that image my accepted image which is that green
uh... checkmark
if uh... we actually take a look at my images folder i have
the green check mark which is called accepted dot p_n_g_ i have the yellow
warning sign which is called warning dot p_n_g
and i also have this little animated gif called loading where the arrows will
spin around.
so anyway um... anytime it's valid that's what we do we go through and we
just load up the green check mark the last thing i do is i have another
function call clear warnings which might just clear out any warning that had
happened to be there previously
in case they start filling out the field and its invalid and then they come
back to it again.
it'll correctly replace the uh... warning message with a valid message
instead.
this show invalid function is just a little bit more complicated it starts
off the same way though retrieving the image tag from the paragraph with the
in path... invalid input field in it and then put in the warning image into it
i then clear out any previous warnings that might happen to be there
then what i do is they create a new span
a new set of span tags essentially
i take the actual message, the error message that is supposed to be displayed
i turn that into a text node and i append that to my span called warning
i give that particular uh... span a class of warning which had been used
with css to style it
i get an i_d_ which is the same as the input fields i_d_ with underscore
warning at the end of it
and here i actually then take that warning spanand i append it to the
uh...
paragraph, the paragraph which is the parent node of the input tag.
the very last function here i have that i've already written
is the clear warning uh...
function
this one is just meant to go through and clear out any warning that might have
already previously been there in a uh... paragraph, in one of the paragraphs with
the input fields. it goes in and checks to see if there is a warning uh... in
that particular paragraph
and if there is what it does is it retrieves that warning and then it goes
to the parent of the warning
which is the paragraph, it tells the paragraph to remove the child
which is the warning.
so it actually gets rid of it there. and as you saw a minute ago everything looks
like it pretty much works just fine if i reload here and start off fresh,
if i leave the first name field i get the warning, if i go back to the first name
field and put something in its not blank anymore so the warning goes away and i
get the green check mark instead.
so everything is functioning just fine the way it is right now and what we
then need to concentrate on next is going back and actually putting something back
here into the check username function,
which will then utilize some ajax code that we will write.
so then moving forward
uh... basically what i'm going to want to do here with the check username function is
i'm actually going to have a couple of layers of checks here.
the first check is that i'm simply going to want to make sure that they're
actually is a user name given in the username field
because if there's not then obviously it won't be valid and i don't
see any point in actually sending a request to the server in that particular
case.
so i'm gonna start off by saying
if uh...
uh... this dot value dot length
is greater than zero
meaning if there is actually something filled in this field then this is where
we're going to do our ajax call
otherwise
what i'm actually gonna want to do here at this point is simply show that this
thing is invalid so i'm going to go ahead and just copy one of my show
invalid function calls and say you
uh... uh... cannot leave
this field
blank, there we go. lost some letters for some reason.
so let me just leave it at that for the moment and see how that reacts if i come
back over and reload my form again i come down there to my username field and then
leave it again
i get my warning message that you cannot leave this field blank
if i actually filll something into it and leave it
right now nothing's actually happening it's just leaving the message
that was already there previously but of course the next step here would be
that i want to actually go ahead and do the ajax call and then based on what
value i get back from the ajax call
i'll then determine whether i want to uh...
mark it is valid or not one way or the other.
so what i'm gonna do here is before i actually do the ajax call i'm gonna call
my show warning function.
...not show warning... i'm sorry show waiting.
my show waiting function then i'll have put in a little spinning icon to
let the user you know that there actually is something occurring there.
if i come back and take a look at that again in my browser
if i type something in and leave that's what my little waiting symbol is going
to look like that lets them know that something is being processed in the
background. or at least that's hopefully what they'll understand it means.
now for the ajax call itself
what i want to do is i actually wanna put together all my ajax uh...
functionality and put it over in a separate file so that this will be
something that we could potentially reuse
again in the future. let's say i'm gonna call this uh... ajax request
that's what i'll actually call this function that's going to be doing this
now the ajax request itself is going to need some information to go along with
it
first and foremost it is going to require a u r l
the u r l is basically where this request from javascript will be sent and it's
that url on the server uh...that will then be needed to
uh... actually check and see if that username is available or not and then
return the value back.
so let me show you here what i actually have running over on the server.
here on the server side of my application what i've actually done is
set up a server-side script this was actually written in ruby on rails
and basically what it does is it lets me form a url that looks something
like what i have appear in my address bar h_t_t_p_ colon local host because
it's running on my local machine
port three thousand and then go to the users
and then right here is where i actually put in the username i then follow that
with slash check dot and the format that i want the request to be returned
in. so if i actually hit enter right here it takes it just a second to
load
the reason it takes it that second to load is i've actually introduced a uh...
uh... sort of a false sort of uh... make believe one second delay
the reason i have done that
is so that it will simulate a little bit more closely the user's experience.
with the client and the server both running here on my local machine if i
didn't put in that fake delay it would return almost instantaneously which is
certainly not what will usually happen with the user. usually there'll be at
least a little bit of latency that will slow it down a bit so i've put in sort
of an automatic one second ... latency all the time.
but here when i put in this particular url, basically submitting noah as
my uh... submitted username what i see show up down here in my browser window's just
the word false but if i actually go and look at the code for that page what it's
given back to me is a valid xml file, a valid xml data this first
line is just saying what version and type of including the xml was in,
i then have a set of hash tags which are pretty much just sort of a uh...
left over from the particular quick and easy technique i used to make this data
and then the most importantly what i have in here is i have an xml
tag called taken, i just made that up
it's type is boolean and that's insignificant to us but the actual value
of the taken tag is false so what that's actually telling me is
is the user noah name...
is the username noah taken?
and the answer is false it's not, it's available
if i were to come up here and put in a user name that is already taken
victrola
there's my one second delay
and it comes back with true so this is the xml that was returned in this
case.
so more or less the question we ask is is the username victrola taken and it
came back and told us taken is true
so that's what we're actually going to be dealing with here initially on the
server and just for your reference
i've created two users on my server already
that have the username victrola and bernard so we have a little bit of test data
to work against.
now as far as the actual u r l for the uh...
javascript goes for our ajax request goes what i'm actually going to do here is i'm
gonna pass in this url as a string
except instead of actually having victrola hard coded in there i'm going
to append in
the value of this particular field so whatever the username or whatever the
user has filled in to the form field for username that value is what will
actually get put there into the u r l
that's what will then cause eventually the request to be sent to the server
and the server will return data to us uh... letting us know whether it's taken
or not
besides the u r l, the ajax request also is going to have a number of different
options that go with it
um... the actual ajax call uh... down in the guts of javascript that we will deal
with here in a few minutes we're gonna find
let's us do things like specify what type of requests we want to have sent
basically is it gonna be a get request or put request or post request or delete
request.
um... a lot of times we're just going to want it
to be very simply using a get request just for the simplicity of it but it
would be nice in the future if we were able to modify that, change that, if we
decided we needed to use the same code for some other purpose.
another one of the options that the ajax request might need is uh... dealing
with the uh... a synchronous behavior of the request itself
the way that w'ere actually gonna end up putting in the ajax request is we have
the option of making it synchronous or a synchronous. now surely we're going to
want to be a synchronous the majority of the time
but again if we ever run into a situation in the future where we do want
it to be a synchronous request basically meaning it won't go until the page is
reloaded
then i want to be able to specify that too.
so the way i'm actually gonna set up this ajax request function which we still
haven't written just talked about a lot, is the second argument i'm gonna pass to it
is just going to be an object in that object will be something that in the
future i could possibly populate with values, which may mean uh...
make it synchronous or use a different uh... type of request a different method
than get.
but that's what i'll have for right now.
the third thing i'm gonna wanna put in here is what would generally be called a
call back.
basically a call back is actually going to be a function here so i'm actually gonna
pass a function to my function is kind of the idea so my first argument is the
u r l itself right here
the second argument of course is an empty object at the moment and the third
argument is going to be a function that i'm passing.
basically the role this function is going to play is that whenever this function
is...
is past to my ajax request function, the ajax request function will go
through all the generic workings of forming the ajax call, sending it off
waiting for a proper response,
and then when that response is returned it's going to need to know what to actually
do with it so the idea is going to be that once the request actually comes back
once the response i guess i should say actually comes back we're gonna have it
actually pass it to this function.
so i'm gonna tell this function that it's going to receive the request object
which is going to have the response data stored within it.
and then here inside this, this is where we will actually been do our work
here i'll say uh
process
response for right now.
but before we deal with that part of it we need to actually go and get this
ajax request function put together so
i am going to create a new file called i think i'll just call it ajax
that's usually when i call it
and i'm going to uh... make that file available here to my html page by
importing it
i'm going to do an import for uh... javascripts that's the name the folder
it's going to be in and the file's going to be called ajax dot j s.
here's the actual ajax dot j s file itself right now it's empty but this is
where i'm going to put in all of the actual ajax workings, starting with my
ajax request function
which i've kind of uh... already called in a way
from my other file.
let me just put a comment there, this is going to be a little bit long so i'm gonna
comment that closing brace.
now from our other file what we were actually passing this function is we're
passing it the u r l
we're passing it an obj...an object which i'm gonna call options and then the third
thing we're passing is the function which i'm gonna call "call back"
now actually into this function, uh this function is gonna deal quite a bit
with a request so i'm going to start off here by creating a request object and
just setting it to null
i guess it's not really an object at this point, a request variable
that i'm just gonna set to null for the moment and...
and here in a minute we'll see how to actually make that request that will do
the
uh...ajax part of all this.
the other thing i want to go ahead and do is resolve some of the different
values that may or may not be present in that options object that i'm passing
as the second parameter to this function.
uh... right now i'm thinking that there're probably two different values
that i'm going to want in there, going to want a method
and i might want to specify whether i wanted to be synchronous or
asynchronous.
uh... maybe i'll call it sync
there we go.
so what i'm gonna do with these two is i'm basically gonna say from the options
object if there's something called method
in there
then take it
otherwise take a value called get
for synchronous, i'm going to say in the options object if there is
something in there called saint take that value otherwise take true
so i am essentially
uh giving myself the ability in the future to set either one of those two
values.
but i'm also setting default values the values that i expect to use most
frequently here so that if i don't put anything i will always gets sort of the
regular default working the way i would normally want it.
so that's most of the set-up and what comes next then is actually getting into
the actual ajax itself. this is a little bit like some those cookie examples we
did where the setup is far more complicated than the actual focus of the
work itself.
but we are actually finally there've doing the ajax
now basically the way ajax works
is that uh... depending on what browser you have your going to have an
object available and that object is what is going to essentially enable you to
make these a synchronous ajax calls.
the only trick to doing this is that every browser in the world uses one
particular object and then there's one browser, internet explorer, that uses
something different from everybody else.
so to do this correctly we actually have to figure out which of those two objects
we have
so what i'm going to do is i'm going to to start by putting an if statement i'm
gonna say if in the window object there's something there called xml
dot h_t_t_p_ request
then that means that we're dealing with a
non-internet explorer browser.
and this is the object that it'll have so that'll be the object that we
actually go through to do the rest of our ajax work
if it's not internet ...um...if it's not not internet explorer i guess you could
say
then i can check to see
if i had something available in here called window dot
activex object
which is the way that internet explorer does ajax
so
let me put in a comment here
uh... this is for i.e. this one is for
non i.e.
uh... essentially what's gonna end up in both of these is going to be pretty much
the same but there will be a couple of tiny little minor differences. so let's
start off up here the way we would do it for every browser that's not internet
explorer
what we need to do first is we need actually generate our xml h_t_t_p_
request object. i'm going create that object and then put it into my request variable
i'm going to do that simply by saying that i want a new x ml h_t_t_p_ request object
basically just like that
uh... once i actually have that request object there is going to be a few other things
that i want to do with it
uh... one of the first things i'm going to want to do
is i'm going to want to set it up so that uh... it can automatically call
another part of my javascript code here
whenever it uh... undergoes what's called a state change.
basically then what's gonna happen here is that when we actually send this
request
uh... every internet request goes through a number of different steps. there's a step
where the request is ready but it hasn't actually been sent, there's a step a
state i guess i should say
where the request has been sent, there's a state where the request has been uh...
received by the server but not yet replied to,
and then finally there's also a state where uh...
the server has replied ... and the reply has been received back
here in our javascript
and what we need to do is we need for our javascript to be sensitive
to what state the request object is in end
so that when it goes into the proper state we then know that we've received our
value back and we're ready to start dealing with whatever it happens to be
so we can keep track of these different changes of state by using the on ready
state change event which is built into the request object and what i'm gonna do
is into that particular
uh... event
i'm going to put in a new function
and in that function i'm going to have it call another part of my javascript here
which will actually be in charge of monitoring the request and then dealing with
it once it's complete
uh... let's call this um...
uh... function that i'm gonna call here state changed
and to the state changed function i'm going to pass
the actual request object because that's where the response will be stored
and i'm gonna pass it the call back because once the request is complete
it's the call back that it's gonna want to call
and uh... give that request to.
so anyway that takes care of that part probably clear as mud if i had to guess.
the next thing we need to do is we need to actually open the request object we do
that using its open method
the open method needs to be given the actual method of the requests so
basically is it get or put ... get or put or post uh...more or less
what we set up here and get by default
we need to give it the actual u r l that the request is going to be sent to which
was one of the parameters that i passed to this particular function
and then i need to let it know whether it's gonna be synchronous or not. which
again is one of the values that i got up here from options or sent to a default
value so by having true there that's going to mean doing it asynchronously.
the next thing i need to do then
once the request is actually opened and populated with the correct data is i
need to actually send the request
so i'm going to say send the request i'm going to pass it null
i have to be honest i forget exactly what that null stands for but
with the non internet explorer version uh... i do believe that has to be there.
so that'll more or less be it. that will create our uh... our ajax request
object, tell it what to do as it goes through the different changes of its life, it'll
open it and it will send it.
what we need to do next then as we need to do is essentially the exact same thing
down here in case we're dealing with internet explorer
if it's internet explorer what we're going to do to do
is we're going to get our request object
uh... by doing a new
active x
object.
uh... when we call the activex object here we need to pass it
microsoft
i misspelled that
s_o_f_ t
microsoft dot xml dot http and that's what will actually tell activex
apparently in this case to create a ajax object... an ajax request
object so that this can be accomplished.
what I am going to do next then is gonna be essentially the same thing i did up here
so i am just going to copy that
code uh... the changes are going to be fairly minor
the on ready state change business is going to stay exactly the same, the
opening of the requests is gonna stay exactly the same, when i send the request
though no null
there
otherwise pretty much everything else is identical.
so that more or less takes care of the actual ajax part of it that will make
sure that the actual request is sent to... sent to the correct place in the correct
manner and everything will be fine.
hopefully.
so what we have next then is we need to deal with the state changed methods so i'm
gonna come down here in my file and i'm gonna add that method now
there we go.
here in the state changed method is where we need actually deal with the request
when it is uh... going through its what i think of as being basically its changes of
life.
uh... through the different states that it's going to occupy as the request
progresses.
so
uh...
the request itself like i said has different states each one of those
states we're going to be able to find out what it is
by looking at a attribute called uh...ready state ready state
that's uh... state s-t-a-t-e
that's available from the request object and what we want is we want ready state
to be equal to 4.
or that basically means that the requests is complete
so i'm gonna put this into an if statement
so more or less the state change method will
ignore all of the different changes at the request object goes to the
through
until eventually the ready state becomes four, which at that point should mean that
it is complete, the requests is complete and data has been returned.
now just because the data has been returned doesn't necessarily mean that
the request went well as all of you probably done at one time or another you
know that you can type in a bad u r l
and get back a four oh four error,
or something like that,
so what we want as we actually only want to proceed from this point if the
request objects status,
which is another attribute available in the object is equal to two hundred
two hundred in this case would mean success. It would mean that the request
was sent to the response was received there were no error
that anybody was aware of. right
The last thing I'm going to then as i'm gonna say if we have a call back, meaning if the
call back is not null,
which it potentially could be
and what i want to do is i want to call that call back function i wanna pass at
my request object
so that's pretty much all i'm really going to need there
it would be a good idea probably if I threw some elses to go along with these
may be some little alerts in here to let users know about errors,
more realistically would probably be a good idea of these things were actually
additional call back type functions so that i can kind of customize the error
behavior to that particular application but for now I'll just throw in
some alerts.
here in this particular
alert i'll say uh... let's see what i want to say, I'' say problem
receiving the data.
down here maybe open another else in, this one's for the ready state
for this one and uh... actually i don't want anything for this one because i
don't wanna chirping away every time the ready state isn't four because that
would be very expected ready state won't always be four. so i know i think I'll
leave that one off.
alright so that more or less gets all of that put together at this point i think
we are ready to
kinda give it a first dry run test. we just get that out of my way
and see how it actually behaves uh... what should happen now
is if we come back and we look at our check username function
the check username function will make sure that the
uh... value in the username field is greater than zero if it is it'll show
the waiting symbol
it'll then do the ajax request
and if our ajax requests a successful at will call this function right here and
it should pop up an alert that says process response
so let's give it a shot and see if it works.
I just reloaded it here in my browser
if i go to my username field and then leave it again
he tells me can't be blank
if i go to the username field and fill something then
i get my waiting mark
and there we go process responses come back so it's called my call back
function
technically at this point in the process the data that the server
returned is actually sitting there in that request object so all we really
need to do now is actually deal with it.
so here inside the uh... my call back function instead of having an alert in
there this is where i actually now want to go about dealing with my
uh...
dealing with that actual response uh... doing whatever it is that i actually
want to do with it
what i essentially want to do with it as i want to take that xml data that the
a server returned
and i wanna pull out the part of it thats actually important to me
so what i'm going to do is i'm gonna create a taken variable and in that taken
variable. to get that taken variable
I'm going to the request object
the request object as in it a data member a uh... variable essentially
called response xml
which is where the external data that was returned as actually stored
because it's xml now what i'm going to do is i'm gonna tell it that i now want to
document element that basically gives me the route of the xml
uh... basically the hash tags that i had that we saw on there previously
and then from the hash tags, what i'm going to do is i'm gonna tell it that I
want to get elements
by tag name
and the actual element i want to get the tag essentially i want to get, it the
tag called taken.
now sort of like we dealt with before uh... get elements by tag name is actually
going to return an array. I should know that there's only going to be one
element in that array.
so i'm just gonna go ahead and put a subscript of zero right there to go
ahead and give me that very first element on it. that linegot a little bit long
There we go, I'll just indent a little bit less
uh... so it all stays on one line, hopefully looks a little bit less
confusing that way.
okay
now at this point i should have the actual taken tags stored here inside
my taken variable. what i'm gonna want to do at that point is i want to
delve into that taken tag and actually get the true or false word out of it
so i'm going to say if taken dot first child now we should be the uh... text
node that's actually inside that elements
then i'm gonna put dot data which gives me back the actual text itself
i'm gonna say if that data is equal to the string false
then false is going to mean that their
uh...
and false is going to mean that the username is not taken uh... gotta keep
that straight my mind
so if the names not taken
that means everything's good so i'm going to show valid
uh... with show valid when i'm going to do is i'm going to pass it this
uh... show valid needs to know what uh... which area of the form to actually
put this into
but but this right here in think he's actually going to give me a little bit
of trouble uh... this worked fine when i used it up here.
but it will not work ok out down here. At least I don't imagine it will. We can
go ahead and give it a test
just to make sure that i'm right about this
type in something here
and sure enough he see nothing ever happened if i go and take a look at my
error
their should be something related to this uh... result intered expression
input dot parent node it is not an object, so it's talking about line eighty
nine
uh... i'd be willing to bet that's in my show valid function
eighty nine sure enough
right here
so whatever i'm passing is this at that point does not have a parent node which
is causing an error.
uh... what's actually occurring here as i have a little bit of trouble with
what's called a closure.
essentially i have a variable here sort of in the outer part of this outer
function call check name
but inside check name there's an inner function this anonymous function in here
just called function and in this particular case this has a different
value
uh... it has to do with the way that javascript actually handles the value of
this what i'm gonna do appear
is i'm going to create a new variable called target and an assigned this to it
what that'll then that we do is refer down here to target and target will
always be whatever this was at this particular point in the code
closures can be a little bit confusing in javascript something you might want
to practice with a little bit maybe i'll put together a future episodes about
closure. thay maybe help clear that up a little bit
But one way or another the false is there then show valid to true is
basically the idea
if uh... false is not there then we're gonna show invalid
we're gonna pass it target
along with an error message i'll say that username
is taken. That U right there's bothering me
so see how that works
back over to my form. I'm gonna reload go to the username field unfocused that
left blank, it caught that.
if i type in a username that's taken
victrola
as soon as I leave i get my one second pause and then sure enough it comes back and
tells me my usernames taken. if i put in a different username, noah
focus one second pots and now it's time it's ok so it looks like it's
working just fine
retry putting in bernard
this should be taken
turns out it is.
so looks like our ajax is behaving they're just exactly the way that we
would want it to,
and hopefully the way that we've got our little ajax uh... file put together it
will be something that we can reuse in the future
simply by passing different options to a different urls and can take care
of most of our ajax needs.
i mentioned to you back at the beginning that
even though it's called ajax, asynchronous javascript xml,
xml doesn't necessarily actually have to be the data format that's used
for returning a response from the server.
if we actually come back over and take a look at my server again this is where i
was actually retrieving my xml data with my u r l
i actually set the server up so that instead of putting dot ajax or dot xml
at the end if i instead put dot j sign
what it does is it returns the exact same data to me and json format in this
particular case my browser is not exactly sure what to do with i to it
actually downloaded it, but if i come in i take a look at the file that it
downloaded
this is what was actually in it, it's essentially
the exact same data we saw before with the xml except now it actually in
javascript format. javascript object notation
so as hopefully remember from before the curly braces mean it's an object
this object has an attribute in it call taken and that particular
attribute has a value of true
so when we're dealing with this kind of situation a server returning a value
back to javascript having the server
return this data in a javascript format can sometimes simplify
the actual handling of that data when it's returned so a lot of this business
that we had to go through with the xml to retrieve the actual bit of data that
we wanted
can essentially go away
if we're doing this with uh...
jason instead
so i'm gonna do here's i'm gonna comment out the external part of the uh... uh...
handler
as a matter of fact what i think i might do is let me just comment out this entire
request
uh... i'm gonna copy and then commented out let's just sort of rewrite I'll paste it
back in. instead of doing all this stuff in the request let me take that
out and up here on my u r l
instead of asking it for xml data i'm gonna tell it I want json data
instead
Everything up until that point should work thethe same will still end
up here but in our call back function but now our call back function in the
request object will receiving uh... json data
instead of the uh... actual xmldata
what i'm gonna do
is i'm gonna create a variable here i'm going to call response and i'm then
going to assigned to that response variable
uh...
the uh... well basically a set of uh... parentheses
and inside that setup parentheses what i'm going to apend in here is going to
be the requests
uh... response
text attribute
now you might remember appear before when we were dealing with the request an
x ml the date it was actually stored and i think all response xml
here because the data isn't x unalloyed something else its return to us in a
format cold response text.
did i spell that right yeah i think that's right
by actually taking that response text putting a set of parentheses around it
and giving it to the eval function what will happen is that
response text will stop just being text and will instead turn into an actual
javascript object here called response
uh... so what i'm gonna do next and as i can just go straight to working with it
there's really nothing else that's particularly required here
i can just say if not
response dot taken
so response of course is the object the object hasn't attribute it called taken
which is either going to be true or false if it is
is uh... false they not sign will make it become true
and in which case we know that our response uh... our username is not taken
so i can just say show valid
and i'll pass it target same way i did before same reason and
otherwise i will show invalid
and uh... here i need to pass at the target again
and my error message the username maybe I should make it that user
name
it's taken
something like that
so it's not a huge difference or at least not in this particular case of
course this particular case is fairly simplistic since there's only one value
that's being returned from the server
uh... but given how much data is being returned that one value it did save us a
little bit of complication i would say and you can imagine that if we were
returning five or ten or a hundred values from the server
having it actually here in sort of a native javascript format certainly does
make the handling of that data much more simple
which will give it a try and make sure that it
works.
reload my form, username blank,
can't leave it blank
username that's not taken one second pause
and everything's good
put in a user name that is taken
one second pause
and it recognizes that it's taken
username its not taken
accepts that username that is taken
there we go
so that works just fine working with json data is typically my preference.
when i'm making ajax calls from javascript that might not always be an
option
but when it is an option especially when you're handling both the server and the
client side of things you can usually make it an option if you want to
and uh... it certainly does make things quite a bit more
uh... streamlined to be able to handle it that way