Better SJR debugging

SJR stands for Server-generated JavaScript Response. And I love it! It is such an easy and wonderful way to add Ajax into your application. You just generate a simple JavaScript code on the server and that’s it.

SJR debugging

SJR debugging is cumbersome. It is not hard, it’s just cumbersome. When an error occurs for an XHR request then nothing is shown in the browser.

You don’t even know if the request was sent or not. You have to either check the server logs or use the browser developer tools to see what is going on and what error happened.

Standard SJR debugging

Better SJR debugging

There is an easier way to debug SJR. We can display errors immediately when they happen:

Better SJR debugging

I’ve created a Rails pull request with this feature, but it is one month old and there was almost no feedback in it, so I doubt that it is ever going to be merged. Anyway, if you find this feature useful, then please support it with THUMBS UP on GitHub ;).

Thumb up please!

Better SJR debugging with rails-ujs

There is another way to show SJR errors without any modification to Rails itself. jquery-ujs is going to be replaced by rails-ujs in Rails 5.1. And with rails-ujs it is really easy to handle this on the client side. We just need to listen for an ajax:error event and when it happens than show the response from the server:

# app/assets/javascripts/

<% if Rails.env.development? %>
  document.addEventListener "ajax:error", (event) ->
    alert event.detail[0]
<% end %>

That’s it. These four lines of code will do the job. The only thing which I don’t like on this solution is that YOU have to add these four lines into your codebase by yourself. I would like to have this functionality in every new Rails application. I just want it to be ON by default so I do not have to take care of anything.

Maybe it could be added to rails-ujs. Maybe it could be added directly to Rails (with my PR). I am not sure what is the best place for this.

Alert box? Really?

Yeah, really. It is simple and effective. And it is usable in Chrome, Firefox and Safari.

Alert box in Chrome
Alert box in Safari
Alert box in Firefox


I am not saying that showing an alert box is the right and the only way how to improve SJR debugging. I am just saying that there is a place for improvement and I would like to open a discussion about it. If you have any ideas/opinions please share them in comments. Thanks!

Read this next: How I work on my spoken English