London London - 5 months ago 10x
Javascript Question

Encode string javascript so that it can be transmitted to a server

I'm trying to send json string in the get request to the server, here is how it looks before encoding :


Naturally I end up with null pointer when trying to get this json string, then I googled this encodeURIComponent and it partially encodes this string like this :


But this is how it supposed to be in order to work :


How do I get this, entirely encoded string so I can read it at server side properly ?

Reason why I used get instead of post

I'm sending this filter(json) content to the server side, web service gets data from the database and returns pdf document.

Using post, I'm able to send correct data and the response is successfully displayed in my firebug console. But I need to return pdf doc to override the current page or open new window/tab and return in that one.


I think you're overworking this problem. Or encoding too many times. Or something. You've got a JSON string, and you are trying to JSON encode it. That seems...unhelpful.

A better approach might be to produce a Javascript object, then JSON.Stringify that, and then transmit it as a parameter.

var thing = {
  groupOp : "AND",
  rules : [
    { field : "countrycode", op : "eq", data : "ARG" },
var stringrep = JSON.stringify(thing);
// post via jQuery
  type: 'POST',
  url: url,
  data: stringrep,
  dataType: 'json'
  success: function() { ... },

Normally for a JSON stringified message to or from the server, you'd want to use HTTP POST. HTTP GET puts all "parameters" in the URL; there is no message body. In contrast, HTTP POST allows you to attach a message body to the HTTP message, which can be "anything". With that approach, you don't need to url-encode the quotes and spaces; the JSON message just gets transmitted as the message body of the HTTP message.

HTTP POST is the way applications upload images, or transmit XML documents, and so on. Anything complex gets transmitted via POST.