Last Updated: February 25, 2016
·
3.958K
· alexisraca

Encoding JSON in href using encodeURI, Rails parsing

This is a realy simple but confusing situation, I searched for a while but didn't find a right answer concerning Rails.

Using Jquery we can add parameters to a url to send into server upon clicking, this might be an easy solution for NON FORM cases when you have to dinamicaly send ids, data, etc to the server.

First of all lets imagine we have a JSON:

json_data = {"1": "data1", "2": "data2"}

This is easy to send using ajax

$.ajax
  format: "json"
  url: "some/url"
  data: {"mydata": JSON.stringify(json_data)}

Up there that will send a request to the server with the parsed data for handling, but what if we want to send it via a click to redirect the page using a refresh request and not a normal ajax?
we will have to use one of many solutions like using forms and submits, relocate the page, etc..

For this case we will use a solution where we send the parsed json into the links href to send into the server upon clicking

To do this lets imagine we have a link:

<a href="some/address" >mylink</a>

Then we use this coffeescript:

$("a").attr "href", $("a").attr("href").split("?")[0] + "?" + JSON.stringify(json_data)

With that the json is added to the url but will cause a server error bad request because the json is not URI friendly yet, to do this we add encodeURI or encodeURIelement depending on your unicode.

$("a").attr "href", $("a").attr("href").split("?")[0] + "?" + encodeURI(JSON.stringify(json_data))

This will make the JSON data friendly to the server, but theres still a problem... rails is kind of moody with key values, and this will be shown on request:

{ "_method"=>"get",
  "authenticity_token"=>"C0/ye7xMH2Yvkvr7gM63EGRnTi+BUbQPZ0xsoDv0P8w=",
  "{\"1\": data1}"=>nil,   // we have a problem here
  "action"=>"xxxx",
  "controller"=>"xxxx",
  "locale"=>"en"}

Do you see the => nil ? Well thats not good... we can't handle that on a clean way.
to solve this we have to add the key to the URL for our parsed json.

$("a").attr "href", $("a").attr("href").split("?")[0] + "?mydata=" + encodeURI(JSON.stringify(json_data))

This will result in a clean hashlike json:

{ "_method"=>"get",
 "authenticity_token"=>"C0/ye7xMH2Yvkvr7gM63EGRnTi+BUbQPZ0xsoDv0P8w=",
 "mydata" => "{\"1\": data1}",   // much better now don't you think?
 "action"=>"xxxx",
 "controller"=>"xxxx",
 "locale"=>"en"}

As an extra, the equivalent for an ajax request like this is this:

$.ajax
  format: "json"
  url: "some/url"
  data: {"mydata": JSON.stringify(json_data)}  // thats why we have to add a key always

The conclusion is that we need to understand RESTFUL URLs, they are very easy but strict in the way they need to be parsed to work properly.