Hey guys in this video we will be looking at implementing an AJAX form for our application.
No.
The reason we would use an AJAX form which is javascript mechanism is to reduce the number of reloads
for our pages and I'll do recall that when we're creating an enrollment we want to.
Then not Michaeli one search for students which is why we implemented here Jake UI auto completes widgets
in our textbooks and to add to this functionality what we will be doing is implementing what we call
an AJAX form an AJAX form will actually reduce the need for us to refresh in between clicking or submit
button to recall that every time we could create it actually is set up in the controller to navigate
to our list while we want to do is allow the user to continuously enter and enter and enter on this
one page without needing to navigate so we come back.
So that is where the Ajax form will play a huge advantage.
So the first thing that we will want to do is actually include some G query libraries and we will do
this through new get.
So we will go over to our project right click and go to money can get packages because you don't have
them installed.
We will actually go to browse and we will look for J.
Query on obtrusive Ajax so we can just type but I guess you can just type Ajax and just by typing Ajax
the top result is our library that we're looking for.
So Microsoft that J.
Caught on a true on obtrusive data so we can just go ahead and click install and alone you get to do
its thing
part and with the success of that we can just confirm in our scripts folder that we know have declared
dot on obtrusive agents.
So those are the two new files that we expect to see after you get us completed its installation The
next thing we want to modify is our bundle config so we want to create a new bundle for or new script
files now I'm just duplicating this new query Atlanta named the J query dash Ajax and instead of trying
to retype this I just copied the name from the file here in source explorer and just space that it to
expedite that whole typing process.
After saving this nine to our bundle config then we want to let our little page know that there is a
new bundle in tone so I just include it on the Neath or G query line.
So no order matters as long as it's underneath the Jake or a line then you should have no problem.
So J query dash Ajax is our new bundle that needs to be rendered so we can head back to our creed view
and then we'll start our modification.
So the first thing we want to do is change the type of form so we would see that we're using HDMI begin
form meaning we're using our regular HDMI form the new type of form and tone is Ajax so I see Ajax right
here replacing each demo and we're beginning our Ajax form.
All right so we're seeing that Ajax has a little error underneath its end that's chiefly because our
Ajax form actually takes a few parameters so we'll go ahead and fill in these parameters and I'll walk
you through it step by step.
The first into is the post action so the thing is when the Ajax form submits it needs to know what's
in the controller should I be calling.
All right.
So we all know that the form the HMO form by default will call the post option of whatever is in the
controller.
So we have to create here which renders the form initially and then once you could submit it's automatically
going to look for the DP post version of creates over with the Ajax form.
And even with the H M a form but it's required for the H Ajax form.
We need to specify what action should be called.
So I could specify that I want to call create but then I'm going to modify it a bit and I'm going to
create another one and then we'll write that action together someone to call this one add students make
stuff we need to specify which controller is this action in so it's the controller and then we need
to add new Ajax options and just bring the line here so that we can just fill it out within full of
you know the options are more like properties of this new class so you notice that this is getting the
color coding from visual studio that it's a class.
So we're just adding values and certain properties that are called Ajax actions.
So the first one that we're going to add is the HDP method.
And today it's we've been using post so we can just maintain that so we just specify that we want to
post and then we can see on success we wish to do a certain action.
And I'll call it.
I did.
All right.
So upon success of this post call then we want to call this function.
And another one on failure.
We want to do this one
there are quite a few properties that you can actually implement in the Ajax options section and I have
attached the documents to this letter stating each of those options and how you can leverage them.
The next thing we want to do is implement our new function called IDE students a well or new option
called IDE students and we'll just go over into our controller and I will add it below the existing
post create function.
So like we stated this is going to be an issue TTP post and all of it just just knowing.
This is the first you're seeing if that's the word prop and then pressed up twice and that just implements
a property but it's a quicker way to just get public and they can sit in the type you wish.
And this is not a property of course.
This is actually a function and then we are creating the post option students and of course add students
is going to take a parameter or a problem it's a similar to the existing create but then do we recall
that we're expecting only two values really and truly from this form and in previous lectures we would
see in that actually what this does is omit any and that is coming across the field is not listed here
then it won't be included in our model.
So we're going to use that but then we're actually going to specify exactly what fuels we want which
are the course I.D. and the students I.D. those are the two fields that really should be coming from
this form.
So for this Parliament I'm just going to borrow this quote quickly since it's very similar except I'm
actually just going to specify that I want only the course I.T. and the student I.D. since nothing else
is really being added from this form.
No for this action I'm actually going to do a try and catch so I just type try and then double tab and
then it filled out the rest of that cold block for me and then we can start filling out our code.
So I'm going to follow this sputter and cause a lot of the code that was generated for us is still applicable.
The model state is valid is ticking is there any missing data.
So between the two values that we're expecting which our course I.D. and student I.D. is either of them
missing in this scenario.
And then if it is valid then we expect to add the record and return the view.
So I'm just going to copy that and place that in my tribe block and actually I'm going to modify this
just to look like there's someone to make it into an asynchronous method.
So I just put a song and then task and wrap this.
So focusing on the simple I'm lower hanging fruits of this block of code.
What's I'm going to do is say try to do this operation and if it fails then take this action.
So let's first work on the part that does not fail.
So if the model state is valid then we want to add the enrollment seeing the changes but then you notice
that a return type here is wrong because what we need to do is return a Jesus son similar to how we
returned it in whereas that function right.
So we had a decent result function here and we returned Jesus on object so we need to do something similar
for this since this is a Jason results.
We're going to modify this option to be a Jason object that is being returned and then do recall that
with Jason object so you can actually specify the contents of these objects to suit your needs.
So I'm going to specify a custom object that has two parameters.
The first one is going to be is success which I intended to be a boolean someone to say true because
if the model state is valid and all of this works out then it was a success on passing backup boolean
to say is success is true and also I'm adding a message that I intend to display it to my user someone
to see.
I want to say students did successfully and then following the pattern of our previous G son function
I'm just going to pass the GST on request behaviour low get foreign metal so that or Jason object is
complete.
So let me just review this.
We're trying this operation and if the model state is valid then we're going to go ahead and add the
enrolment added to the database and then return a success so that those with a success message so that
will let or form.
No but we just implemented this or formal no based on what is returned that it was either a success
or a failure.
So we have the success scenario we need to put in the failure scenario.
So far our failure line we can actually just copy this because it would be a very similar thing and
this would be outside of this statement because this only gets done if it is valid and then you'll see
people flip this or maybe you flip it around to see if not valid then return to failure but then if
it is valid then do some others.
So it's up to you but I want to leave this as is.
And so if it is valid then it was successful and if it does not return or if this fails then it will
default to this line so if it defaults of this line which means that the model states is not valid then
we return a failure status.
So our success will actually be falls and our message will be read differently maybe students was not
added successfully so it was added successfully than we expect or just an object of a true for this
value and this message otherwise it should return.
This and in the same vein if an exception is thrown or an exception is courts or other then what we
want to do is not throw because throwing actually crashes our application but we want to handle it gracefully.
So if you're not so familiar with a try catch what this does.
Once again it tries this operation and that entire operation feels anywhere.
Then it catches the exception.
So then you can see okay if there is an exception or an overall error that was unaccounted for.
How do I handle it.
The line through makes the program crash.
In this scenario we don't want our program to crash.
We want the user to just have the same kind of experience as they would have had if it was an invalid
entry.
Then we wanted to show them that it field so we can just reuse.
This is success online and see something different and probably so we wanted to them to please contact
your administrator and then we can probably put in details of the arrow.
You probably don't want to show them actual details of the arrow since they're just end users but if
you're more advanced than you can probably put in like an email to fire off to the administrator or
the webmaster.
When an exception is Scott so that you can keep abreast of the happenings of the software.
No there's one more thing I want to add to this validation before it actually goes ahead and adds a
students and that is I check to see if the student is already enrolled in a particular course.
So what we're doing is allowing somebody from our current view where allowing somebody to select a course
and then type a student's name and then click submit and then it will cause this function passing in
the course idea and the students I.D. and then tried to add them.
What we don't want is a situation where the same student is being added to the same course.
More than once that we're going to put in a validation here and I'm going to add that validation to
this if statement.
So I'm just going to write quick bits of code which is going to query our database.
Some would say var is in the rules equal to and then I can say IDB dots enrollments and then ones use
another link function which is called any which really just says Is there any record in the database
that meets a particular condition.
So as it stands any is going to say is there any record inside this table.
Someone to build on this.
Any function with our lambda expression so I'm using 2 which is our universal letter for lambda expressions
and I'm checking if there is any course iodine in our enrollments table that matches the course I'd
coming from our enrollment model.
Here is our enrollment model coming in through our prior model and I'm seeing is there any course I'd
be in this table.
That is the same as this fourth I.D. which I'm sure would be yes.
My note right.
If you have entered your records in there there should be at least one red card.
Maybe maybe not but this would return true.
But this is not all we're interested in because we want to know that there is of course I.D. That much
is this.
And in that same record where we found out much that there is a student I.D. that matches our enrollments.
So this line once again is seeing these tell me if there is any recording my enrollments table where
the course I.D. and the student's I.D. match the horse I.D. and student I.D. coming in through this
Jesus on request or this post the request to this option in this model object.
So then we want to see if is enrolled then we don't want to have them.
So this is he is enrolled so I can just add I mean this this condition on the statement to see if the
state is valid meaning both properties that are required for the form are there and is enrolled is equal
to forms.
All right.
So if it is valid and the student is not enrolled then we can proceed.
So if either one of these evaluates to not being true then it should pause that the student was not
added successfully and we can amend this NC student is already at it.
The student is already enrolled so it's good to have descriptive messages for each step so that they
know exactly what is happening and probably why feels so I can amend the a system failure.
Once again you probably don't want to tell your users that there's a system failure you can find a nice
graceful message to put there but I'm just giving you the scenarios as they come up I'm helping you
to appreciate why we have customized messages for each state.
So once again we're seeing we're checking that enrolment stable to see if there's any record that has
both.
Course I.D. and student I.D. existing before or current option.
And if there is none then we just see OK return that it was successful.
If there is or if one of these values is missing then we return forms with a failure.
And if there is an error in doing any of this up here then we're going to catch the exception and just
return an error miss it seeing that there is a failure without crashing our program.
No I'm just going to I'm in this line a bit and I said it this way to spell it out for incase you're
new to see sharp I you're not fully familiar.
But then we can actually just see if is not enrolled.
So this actually evaluates to the same thing that was there just now.
So if you prefer to write it this way and this way looks a bit shorter but then you know as a beginner
you may not absorb it as quickly as how I had it before but I'm just showing you that it can be written
either way.
So we're just going to build and make sure that we have no errors.
We are on our project and I'm setting a breakpoint here at our student option so that we can see that
when we click submit the data is actually being passed.
So this function.
So I'm just going to do a quick test here and just going to change the drop zone property and I'm not
going to put in a students I will just see how this behaves someone's a click Create and we see that
our breakpoint is active.
If I hover over my enrolment model we'll see that we have the course I.D. coming back and nothing coming
back for our students I.D..
So if I step through the code and I stepped on to I got to the statements that ran the query and this
returned false because there is no enrollment that exists with course I.D. being for student I.D. being
zero and then I will continue to step and then you see that it skipped over this statement altogether
because the model state is not valid because there is no value being provided for student I.D. which
is required based on our design.
So it hits our Jason objects which is returning that there is a failure in the addition of the student
and there is a message that is OK if a student is already enrolled.
And so sometimes this may not tell the whole story.
All right.
So be very careful with their message because in this case it's not a lack of enrollment but or it's
not the presence of an existing enrollment but it's the lack of valid data.
So you want to be very clear when you have that message.
Any hope we can just press F5 on continue and then we look back at our Web page and we see that we didn't
even navigate a week.
And I'm going to put in a student this time someone's a type for of the students or type.
It is still working.
And then I click Create and then we hit the break point once again and if we look in our object we see
that we're getting a student I.D. And of course I.D. and I am just going to set the breakpoint to the
if statement quickly four to five and then we're getting our statement and we see here at this time
the model state is true because it is getting back valid to valid values for of course I.D. and students
and also is enrolled is fours.
So there is no conflict as to where this block of course should go afterwards if I step in and I'll
just skip ahead of this at another break point and just press at five and then you see that's it it
flashed on the screen because it did this then it did that and then because none of this field it went
to this success portion and it's you see in the students as I did successfully that we designed it to
see and once again if any of this operation failed what would have happened is that it would have jumped
to the cat and then returned that Jesus on Falls also.
So I can just press a five on continuum and you see that the page didn't move.
Nothing changed on the page like that's that's at this stage it's good.
But ah but when I go back to the list I see here that the enrollment that I just did was successful
and yes we're going to modify this speech because as it stands as it is it's not very clear.
We have missed marching columns and poor data.
So this is going to be modified soon but I want us to focus on the fact that the enrollment was added
for calculus and the students as read and the page itself did not redirect I had to manually go back
to the list to see it.
All right.
So that means our agents Ajax form is working as we intended.
So if I look for another student I had one name on Ledford and I could create and I'm just going to
take off my break points at this point because I'm sure it's working.
And then I just continue and the page and refresh the page didn't do anything but then I have to go
back to the list and refresh and then it will yield that that was also a successful enrollment.
And then if I click Create again having already enrolled and Ledford in calculus and I click Create
you see nothing nothing is happening.
Right.
Well nothing is happening visibly so with our breakpoints we would have seen that it heats the code
and it would have evaluated the falls because this enrollment already exists and in the same way if
I refresh this list then you'll see that this is not repeating it's of no matter how many times we clicked
create.
So no that we're sure that our code works what we need to do is actually help the user to be sure that
the code is working because like I said at the beginning there are no visual cues here to see oh it
was successful or it was a failure.
No do recall back in our form we had specified certain options for on success and on failure.
And then we only put in text here but that didn't quite explain at the time what the text meant.
So these are actually functions or names of functions that should be called when it's successful and
when there's a failure.
So these functions will actually be implemented in javascript.
So we have here the scripts block I don't tough to create a new one I just use it and declare a new
function in javascript so you just see a function and you give it the name and I said on success I want
the function added to be called.
And then remember that we're actually returning GSR on object here.
So this is a new object that has two properties is success on message.
So I'm going to prepare my function for the prospect of getting some response from the base on call.
So I'm just using the word as our resource response whatever it is you want to call it.
So that's what I'm calling it.
So once this has finished processing I think got the call about where the response then it cause the
function added I am letting I didn't know that I expected to hose an object in which is going to correspond
with whatever it is I'm returning.
So there is here is going to embody the properties is success and message.
So I'm just going to quickly implement this and I'm going to put in an if statement and see if rez dot
is success then we want to use a Jew query function.
So the dollar sign really invokes a g query call and and this function I want it to render some HCM
elements so I'm going to render an element that's I'm going to call it success I'm calling it but I'd
calling it success.
And I'm want to tell it to feed in fast.
So that's one of those do query things.
So the query makes javascript a bit easier and faster to implement if you were to write vanilla javascript
to accomplish something like this then it would probably be a little a few more lines of code.
So do query act actually expedites that whole process of getting some interactivity in our application
and then I'm just going to copy this code and I'm going to implement another function and call it field
and I'm just going to modify this statement and see if not then I want field to feed in fast.
So I want on access an element called sorry on a successful ad then we want an element called success
the feed in and if it feels and wants an element called field to feed in.
All right.
So after adding these guys I just realized that I would have misled you with something and I'm going
to explain what it is.
Off to show you the code so I did the device for success and field and if we screwed on I just created
one div for field and I gave it the I.T. field of course so that we could target it using the hashtag.
And also I gave the class alerts and alert the angel from our bootstraps that red box will come up and
display our hero.
So what I did here was instead of using the message coming from from our Jason response I where the
student was added or not and then trying to find a reason I just gave a wholesale error right here in
static fixed to say there was an error adding the student to this course and he could say please check
your data and try again or contact their administrator take and explain whatever it is you want here
in one big general takes and also for success I put in the message student added successfully.
So what will happen is that on success we call added and then added is going to check if the success
message is actually true and then render this this function if we wanted to add the text coming back
from the Jason we could just append the text here.
In using JavaScript So this element because res would have raised that message just like it does raise
that success so we could have just said we want the elements of this.
We want to append and do what we want to up and is raise that message.
So that is how we would actually go about fitting that actual error message or success message coming
from our Jason response into the contents of the.
So if you don't want to do it this way where you have the static text in the div then you can do it
this way where you just inject it in.
So I'm just showing you both ways.
I usually just put in a static text but I'll leave that there for your future reference.
No.
When I said I would have misled you I got a bit overzealous and would have told you that unfair there
is corresponds with the Jason response and that was in accurate.
So on failure actually means that if the call to the action fails for whatever reason meaning this was
not successful it made the ajax call and it couldn't find this then what error do you want to show so
this function would actually get called if there was a total system failure when trying to call the
post option.
So that's why on field really means so whether or not on the database side the addition of the record
was successful or if in this case the way we wrote our application if there was an exception trying
to do this operation and it caught our response as long as it's returning our response the Ajax form
sees it as a successful call because it sent data and it got back our response.
So really and truly to facilitate this field versus success scenario for the addition of our properties
for the additional four enrollments to our database then we need to do it a bit differently so I'm going
to see failure here right.
And I mean I can implement a function for this but I don't anticipate at least for this scenario that
my I want a total system failure.
But what I'm going to do is actually modify the added function so unsuccessful.
What do we want to do.
And we call it.
No I did.
Is the reason we're checking for success is that success can be either true or false because we've got
bucket response and it's either true or false.
So if it is true then we want to display our div called success and then I can see else.
So else meaning.
Or is is not.
Or is that success is not true.
Then we can call or all the function which I outlined field and it's possible in there is.
So just to see and we could target that for success and put in the text we can target this.
So this need that therefore your future inference.
Once again I put in the static text here so I'm not going to use this but feel free to experiment.
And so for the added.
If this is not successful and really into that I don't have to do two if statements.
So if it's not successful then I want to call it feel there is someone to take over that block of code
and then what I want to do is just us is just call this function from R S S..
So it's either successful and a good idea and it's a success or failed to add that is the database and
so we're going to display hashtag field div which is a div with alert danger.
So if it was successful that was the alert success.
And this is where you start seeing whole bootstrap makes it easy for you to display visual cues steer
users with very little effort.
So once again unfeeling really means that if it attempted to make the post call this action and it couldn't
find the option maybe renamed it or it just really couldn't communicate with the server then that is
when you call a failure so you could implement another function for failure.
All right all right.
So back in debug mode we're going to test the theory that our code works.
So once again on a successful addition of an enrollment then we expect that we're going to see div appear
and feed inside the animation and we can adjust the speed and you can just take J query documentation
to see the different speed options you can see a slow fast and I think you can see a medium I'm not
sure if the strange and in the same way if it fails then we expect to see a relative to display or failure.
So let us just try.
That's one way to try.
The failed scenario first so I'm just going to click Create and obviously this should fail.
There we go.
So it fitted in.
There was an error.
Adding the student to this course because we have of course I.D. and we didn't specify students and
then I'm going to try and live for two.
Let's see speed up that MVC validation and then we could create.
And there we go.
So we see a little chink in our code nowhere.
We have to do is being displayed simultaneously which is not necessarily what we want.
And you know it's not ideal.
So let's modify our code a bit.
So I'm going to see.
So the modification I mean is to say that if something is added successfully then we want to feed 0
field or you could just set its display to force however you want to do it.
I mean there are many ways you could do that.
So we're just seeing field quickly and feed into success.
And if it fails then we want to feed this in quickly.
You just want to know that when it feels you're not seeing the success and vice versa.
So as we can see more changes here and then try again.
So I want to try to create this field all right so I'm going to try and add to data mining.
And there we go.
So it's only displaying one at a time.
So if I remove this and click Create then you'll see that it replaces the arrow with the success and
vice versa.
So we've essentially added Ajax farm and added a nice clean way to allow people to add students and
enroll them to our class.
However as much as we've done quite a bit of work here the work is still not finished because we still
want more interactive way for them to keep track of who is in what course meaning in order to see who
was added.
We have to go back to our enrollments listing over here and we have to look and then we don't we see
the course but then everything is mixed up yes we can do some clearing modifications and make it ordered
by the course title and so on but it's still kind of mixed up.
So in the next video what we will do is modify this so we'll modify our labels of course and we'll also
modify this entire create view of that based on the course that is selected.
We will see table below here with all of the students in that course and when we change this it will
refresh that view or that portion of this view and show only the students relative to which course is
selected from this dropdown.
Also when we add a students successfully we expect to see them reflected in that list immediately.