Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 :

filters={"groupOp":"AND","rules":[{"field":"countrycode","op":"eq","data":"ARG"}]}

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 :

filters={"groupOp"%3A"AND"%2C"rules"%3A[{"field"%3A"countrycode"%2C"op"%3A"eq"%2C"data"%3A"ARG"}]}

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

filters=%7B%22groupOp%22%3A%22AND%22%2C%22rules%22%3A%5B%7B%22field%22%3A%22countrycode%22%2C%22op%22%3A%22eq%22%2C%22data%22%3A%22ARG%22%7D%5D%7D

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.

like image 868
London Avatar asked Feb 24 '23 03:02

London


1 Answers

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
$.ajax({
  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.

like image 200
Cheeso Avatar answered Feb 26 '23 23:02

Cheeso