jQuery UJS and Ajax with Rails

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
in this episode we're going to take a look at Ajax and how we can do that with the jQuery UJS that rails provides so let's dive in I have created a rails app with the scaffold for books and books have names descriptions and published at dates and what we're gonna do is go into the show action and add a publish button here that will talk to the application it will write the publish that date and then we'll add it to the page which ah the script so we're gonna first start with the jQuery UJS version which should be the simpler of the two but it's definitely more rail specific and you'll probably not want to use this for your bigger applications so let's dive in so this page this show action for the books is where we want to add the publish link to the page and if we just go in here and we add a link to call publish and we'll make up a publish book path and pass in the book and then we'll dive into the routes to make the published book path actually exists so with this we want to create a member action and the member action basically says that for any individual book let's provide these other routes so we were going to add a patch method called publish and the reason why we use patch is so that we can edit the record that's typically a patch or a put instead of a post or get or delete you don't use those for when you're editing a record so in this case we want to patch the record set the time stamp and go right ahead with that so let's add a placeholder here for the published at column in our view and here we're going to display the act book published at attribute and close that paragraph so now that we have the links when we click on this will get taken as a get request to the published path so that's incorrect we made a patch and we want it to actually submit and change the record so when we click on a link by default those are going to be handled as get requests so now our next step is to add the ability to make this link a patch request and rails provides unobtrusive javascript that gets triggered by the method attribute here and we can set it to patch so when we open up our application J's file you'll see that there's a require for jQuery you Jazz which stands for a jQuery unobtrusive javascript and that javascript file basically provides the ability to look for things like this method attribute and then change the way the behavior of this link to actually submit a patch request rather just then a get request so when we refresh our page here if we inspect this attribute on the link you can see that there's a data method that is equal to patch and of course we define that right here so now this JavaScript will intercept this link and when we click on it we no longer get the get request and route problem but we're missing the action so rails map this correctly to the route we sent the patch request and now we just have to fill out the rest of this action so if we open up our books controller now down here at the bottom we can add a publish method and we can have the book and update the published at to the current time in our time zone and here we want to also add the book to get set when this action is loaded so now if we refresh and submit this again we'll get a template missing so this is submitting a patch request but it's still expecting to render some HTML and we're actually loading a new page this isn't actual Ajax because we are submitting the request but we're moving and not actually taking the result we're going to another page so in that sense like we are still submitting data over but we're not actually taking the result and modifying the current page with that and the way we can do that is to go back to our show action and also add a remote is true option so here now when we submit this let's go back to the show action and then now when we submit this nothing happens and that's kind of interesting so what is going on here if we go into our rails logs we can see a big stack trace and we can see that it published it but this time it was expecting a JavaScript response and last time when we did it it expected an HTML response so in your rails logs you can see when it says processing by you can see the controller the action and the response it expects to receive back so now that we've added the remotest true option rather than looking for an HTML response we're expecting a JavaScript response and when this crashed you didn't see anything go wrong on the front end side because the JavaScript here on the front end was expecting the JavaScript response to come back and then it would execute that JavaScript here on the browser and the browser was not being taken to a different page to load so everything that will crash in these remote is true links or forms is those crashes will happen here in the console in your browser so you'll be able to see that when we submit this link you will get enough their error and another err another and you will see that there is a 500 error which means there is an internal server error I mean something on the server happened that crashed when we said submitted a patch request to that URL now the way to fix that 500 error is to actually put in the template into our views so if we go into our app views books folder we can see that the formats that we have are a few HTML ones and a couple JSON responses but we don't have any je s or JavaScript responses and that's what we actually need to build so when you look in the terminal and you see that it says missing template it is saying that we're missing the template in app views books slash publish and published needs to be English it could be a J s format at the script format or xxx crypt format or a bunch of these other formats and then we also have handle errors so these handlers are the extensions that you see when you have HTML ARB you are using the HTML format here and then the ER be is the handler used to generate the HTML so you can mix and match these and in our case we want to edit the app use books published GS dot e RB file and here we can add in an alert just to say hello and see if it's working or not and now if we refresh this page and click publish we can see it says hello so that means that what happens is when you click this JavaScript inter intercepts the click it submits an AJAX patch request over the application server our rails app returns this file and that gets evaluated on the client side so we're returning a string of JavaScript to the browser and it involves the result for convenience and learning this now it's extremely simple so you don't even have to write the Ajax request and the client-side because jQuery UGS does that for you so with this now we can go into our show action and here we're the published at is written let's actually give this a spin and then the ID called published at so that we can select this element on the page huit by the ID attribute and then we can replace the contents of that with the newest published at time so if we do this jQuery provides the ability to use the hash symbol and then give it an ID so here we can say published at and then we can say that we want the HTML of this or rather let's just do text because we don't want to put in HTML and here we can say at book published at because we are using the ER be handler for this view so publish digest out of er B means that the code we need to write in here is JavaScript but we can also add our er B tags in as necessary to generate this code so now if we refresh this page once more you'll see that ok 1750 208 if we click publish it updates the time almost immediately and we can keep doing that and see that it keeps getting published again so it's not loading a new page it's loading this in the background through an ajax request and updating the page with the javascript that we have now there's some gotchas with this if you write incorrect or invalid JavaScript here it's really hard to debug so when you click publish and you have broken javascript there nothing happens you're not getting an error either so that means that the rails application is doing just fine it's loading and rendering that publisher beer but when it comes back to the browser to be eval and you have bad JavaScript it doesn't do anything wrong it just doesn't work you also want to be careful here that the attributes on the model are being escaped properly and that these don't actually insert JavaScript into your response so you don't want someone to add a malicious book in there and have a weird publish that date or description or name that actually has JavaScript in it that gets rendered and executed in people's browser so one last thing is the little fun bonus if you add the data disabled with attribute that I covered in the last episode if you add this to your link and you also make this public publish take a little longer so we're gonna make it let's sleep for two seconds if you refresh this page now when you click publish it changes to publishing and when it's finished it updates and the link goes back to normal so you're able to use this disable with option the same way because UJS provides this functionality and that's sort of the beauty of it allows you to do these somewhat complicated things with only having to define what it should do and it will automatically detect that and add that functionality into your rails app which is really neat
Info
Channel: GoRails
Views: 13,433
Rating: undefined out of 5
Keywords: Ruby, on, Rails, Ruby On Rails (Software), Ajax (Programming Language), JQuery (Software)
Id: CtDjQznAZR8
Channel Id: undefined
Length: 12min 11sec (731 seconds)
Published: Mon May 18 2015
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.