Skip to main content
Javascript and CSS Asset Pipeline:

Sharing Data With Javascript

Episode 100 · January 12, 2016

Learn how to share data between Rails and Javascript without using AJAX



Earn a free month

This episode I want to talk about another method for sending data from your rails application to the JavaScript to be used. JavaScript runs more or less in a separate domain than your rails application. Your rails application just simply generates html that displays this page, and then your JavaScript runs, and it only has access to urls and the data that it returns, so in the past, in episode 96, which you should watch if you haven't already, that episode we talked about using an AJAX request to generate these in-app notifications. These notifications are loaded using the notifications.json url, and you'll be able to see those inside the json object that you give back, which is an array of objects. If we were to go into another browser, and create a forum post, then that user would be able to refresh the notifications url, and see that there's a new notification with the id of number 4. That actually needs to be requested continuously, and this url needs to be pinged over and over again in order for this to show up. Also notice that when the JavaScript runs, when the page reloads, it can sometimes take a second to load up the number of notifications, and then the UI will have to change a little bit to show that you have one new notification. If we go refresh this again you'll see there is none, and then it does the request, and then it's able to parse those. If that takes a little bit of time, then you're going to see your page jumping around, and that's something that can be kind of painful on your first experience. How can we get this information preloaded in the page, so that we can automatically set that up, and display the notification number immediately, no matter how long that AJAX request runs. Well, the way we're going to do that, is we're going to embed json into your html, and I'll show you that now.

If you've watched episode 96, this is the exact same code from that, except that I put a timeout for 1 second so that when the page loads, that little delay happens, and that's going to simulate network latency, that's going to be what you experience in production. You've probably seen Facebook's UI update like that as well. How can we go about preloading this so that it automatically shows that number when the page loads. Let's take a look at our application.html.erb, and let's look at that notification's html that we have on there. This is actually our notification stuff, we have the data-behavior that specifies that this anchor tag is actually part of the notification's JavaScript. If you don't remember in the previous episode we talked about data-behavior tags, and this basically denotes that this html tag and all of it's children will run with certain JavaScript behaviors, and that's just a way for you to decouple the JavaScript from the html tags specifically, and the CSS classes and id's. So it helps you really separate all of that responsibility out, which is good. But this is also very valuable because of those data tags for stuff like preloading notifications into your html. Rather than going and waiting for that round trip, we can actually embed the AJAX here, and maybe we had data notifications, and this is what embedded that JavaScript, or that json object basically. If we were able to embed json here, we would have our JavaScript to be able to look at this tag, pull out that data, and then immediately, when the page loads, show the notifications, and then later it can just go check for updates. Let's actually go do that, let's delete this, and let's go back to localhost:3000/notification.json, and grab all of this json, and then just paste it into this data-notifications tag. Now I'm going to change the quotes here, so that we don't get weird escaping, but that will go ahead and embed the json into the html. So now, if we refresh our page here, we can open up our JavaScript console, and we can just look for data-behavior=notifications, this should grab us back our list object, and it does, and here you can see the notifications, that means we can just call data("notifications") on that object, and we ill get an array of json objects back. This is all the code that we actually need in order to reference that json thats preloaded into the page. So when the page loads, we can go an render immediately. All we're going to have to do, is go into our, and let's comment out this code here so that when the page loads, we'll never display notifications. Here let's actually use that preloaded json that we have on the page, and let's just console.log"notifications"). This is that part that we're already doing in the console, so we just need to use that variable to access the embedded notifications. When our page loads, we should see that same array gets printed out, and it does. This is cool, we've already got that going, and that just means that we now have the array, and as it turns out, that's the exact same data object as we get back from the AJAX request. That means we can just simply call @handleSuccess with that data, and we should be able to refresh the page, and immediately, you're going to see that you get the JavaScript notifications rendering, and they of course will have to wait for the body and the CSS is parsed and the DOM is loaded, but the JavaScript will run immediately then afterwards, and you'll have the most minimal delays as possible for that.

It might be kind of surprising that we can literally reuse the handleSucess here from rendering after we get the json back, but that is all we really need to do. That means you could actually go through and do this, immediately upon page load, and then you can also use that code for setTimeout just to simulate your browser being slow. You can actually replace this with a setInterval, and you can set it up to check for new notifications every 5 seconds, for example, and then you would get sort of a simulated real time set of notifications. That would be all that you would have to change for that to preload them immediately on the page, and then to check for updates every 5 seconds. It's pretty cool, it allows you to really have it easy to work with notification system, and then the last piece that we have to do is to go back here and replace this hard-coded notification with the actual notifications that we get from generating that json. Let's go ahead and do that now. Let's pull in the json that we hard-coded before, and let's replace this with rendering that exact same template that our application uses for notifications. That's the notifications/index.json.jbuilder file. This is the file that you want to render from inside this other template, and you can actually simply do that by calling <%= render template: "notification/index", formats: [:json] %> otherwise it won't look for a partial, and here you say "notifications/index", and because this is an html request, you're actually going to need to specify formats as json in order to force it to render the json format. That's really all you're going to have to do template-wise, but remember, this json jbuilder file is rendering the @notifications variable that is set in the notifications controller. This is the unread notifications for the current user, and we're not going to be necessarily inside this controller all the time. This is the application template, so this is for every single page that is rendered, we're going to need this variable to be queried. Now it's going to be pretty quick, and so we're going to be able to do that to preload it if your servers are fast and scaled up to the point where this is going to be making sense to preload this information. So we would actually need to go into the


before_action :set_notifications, if: :user_signed_in? 

def set_notifications
    @notifications = Notifications.where(recipient: current_user).unread 

That should be all we need to do in order to set those notifications up dynamically. If we inspect that notifications again, we'll see that it's automatically parsed into a json object because the data notifications is already handled that way, which is pretty nifty, and so our really just needs to stay exactly the same and keep this set interval. It might make sense to rename the setup then, and move this out, so you would want to set this up to be run, instead of then, we want to do it there, and then we'll also getNewNotifications() every 5 seconds instead. That should do it, and of course, getNewNotifications should be set to the instance method there, the @ method, and it probably makes sense to also do this inside the if statement. We'll check to make sure that that object exists before we do any of the work with it. These are really the two set up methods that we're going to have now, and then this will just be called every 5 seconds. That means that we should be able to go back to this page, and then go to our other user and say: Hello, and we should go back to this, and if we wait for about 5 seconds, we should now see that number change to 4, and it does.

That is the secondary method of sending data over to your JavaScript, though on the one hand, you have AJAX in order to pull data over directly from the JavaScript, and then you also have your html with extra data hidden inside of it, in order to give the html data to work with immediately. That's something that plays a lot of different purposes, there's a lot of different use cases for this. For example, if you want to make sure your notifications are rendered immediately, then it makes sense to potentially embed that inside the html, and the reason for that is because when you're doing this, sure you have an extra query, and sure you have to render an extra template, but you're actually saving an entire request to the server through the AJAX portion of the code, and that is going to save a whole lot more time, because that would have to also run the query, also render the template, but it has to do the entire stack of rails, so it has to go through and set up the connection, parse the request, prepare the request, do all of the rails stack, and here you're already doing that, so you're just including a little extra data that you know is going to be needed anyways. This is useful as well to send data initially over to react or ember or angular or any other front-end framework, or even just jQuery like I showed here, and that will allow your JavaScript to run instantaneously when the page loads, as opposed to waiting for a request afterwards and doing all of that stuff. It helps include or minimize the request overhead that you have to do in order to get your JavaScript up and running on the client side, and also this is useful for anytime that you're doing something with Stripe for example, so you'll notice that you'll put like a meta tag up here that will include your Stripe public key inside the meta tag, and then that's a way for us to send that data over to the Stripe JavaScript library in order to tokenize the credit card on check. You can use this for a bunch of things, for example, you could even include a meta tag up here that denotes weather the user is logged in or not, not it will enable your JavaScript to know weather or not it can perform certain functions, without having to make the request and see if it gets rejected or not, so it is a way to cut down some of the requests and things just to pass data into your JavaScript that it might need to know. This episode is definitely a little variation from the usual, a little more heavy JavaScript focused, but this is going to be the foundations sort of the react's screencasts we are getting into in the future, because we'll use the react rails gem probably to render the react stuff server side, and you're going to have pretty much the exact same functionality when you're doing that. This is a little prep for that, and those should be coming very soon. Hope you enjoyed this episode, I will talk to you next week. Peace

Transcript written by Miguel


Subscribe to the newsletter

Join 31,353+ developers who get early access to new screencasts, articles, guides, updates, and more.

    By clicking this button, you agree to the GoRails Terms of Service and Privacy Policy.

    More of a social being? We're also on Twitter and YouTube.