How to send getJSON a string with special characters? - javascript

I want to send a getJSON with special characters?
In this case i have a .js file which create the string to send using getJSON methos. for that i use following command.
$.getJSON(strUrl, UI_DesignPecTab.validateResponse);
Using above method i need to send a string like follows :
var ID = "W6"
var headerString = "PT##?" + ID + "Z##;#TKT/#CHK/#BOR/";
But when i send this to server side it fails due to this uri contains some invalid characters? I need to know how can i get this done. I have tried to encode and send this using "encodeURIComponent()" but um not sure is it correct or not? if it correct how to decode it server side in java? For the above method i have used following code:
headString = URLDecoder.decode(pecTabData.getHeadString(), "UTF-8");

Related

removing the backslashes in json string using the javascript

i have JSON response which is having backslashes and some responses are not containing the backslashes.
I need to show error message based on the response, How do i parse the JSON response using javascript?
JSON response with out backslashes,
{"_body":{"isTrusted":true},"status":0,"ok":false,"statusText":"","headers":{},"type":3,"url":null}
response with backslashes,
{"_body":"{\"timestamp\":\"2016-11-18T04:46:18.972+0000\",\"status\":500,\"error\":\"Internal Server Error\",\"exception\":\"java.lang.ArrayIndexOutOfBoundsException\",\"message\":\"1\",\"path\":\"/login\"}","status":500,"ok":false,"statusText":"Internal Server Error"}
i tried in the following way but it is working only for JSON response which is not having the backslashes.
var strj = JSON.stringify(err._body);
var errorobjs = strj.replace(/\\/g, "");
Actually the problem is not with / slashs. The JSON is INVALID.
remove these " from backend server
{"_body":"{\"timestamp\":\"2016-11-18T04:46:18.972+0000\",\"status\":500,\"error\":\"Internal
Server
Error\",\"exception\":\"java.lang.ArrayIndexOutOfBoundsException\",\"message\":\"1\",\"path\":\"/login\"}","status":500,"ok":false,"statusText":"Internal
Server Error"}
double quote before "{"timestamp and one after login"}"
these two highlighted and your code will work.
var data = '{"_body":{\"timestamp\":\"2016-11-18T04:46:18.972+0000\",\"status\":500,\"error\":\"Internal Server Error\",\"exception\":\"java.lang.ArrayIndexOutOfBoundsException\",\"message\":\"1\",\"path\":\"/login\"},"status":500,"ok":false,"statusText":"Internal Server Error"}';
var json_data = JSON.parse(data);
console.log(json_data);
You are actually wrapping body object in string at backend which is not valid.
"body" : "bodyOBJ" //Invalid
"body" : bodyObj //Valid
var obj = JSON.parse(response)
if(typeof obj._body == "string") {
obj._body = JSON.parse(obj._body)
}
console.log(obj);
Solution:
var response = {"_body":"{\"timestamp\":\"2016-11-18T04:46:18.972+0000\",\"status\":500,\"error\":\"Internal Server Error\",\"exception\":\"java.lang.ArrayIndexOutOfBoundsException\",\"message\":\"1\",\"path\":\"/login\"}","status":500,"ok":false,"statusText":"Internal Server Error"};
var body = JSON.parse(response._body);
console.log(body.error);
Explanation:
You have a top level object with one key, _body. The value of that key is a string containing JSON itself. This is usually because the server side code didn't properly create the JSON. That's why you see the \" inside the string. Unless you are able to fix the server side code, you have to decode the nested JSON manually.

Javascript URL encode a string but do not encode again the part of string already encoded

I have something like this:
<script id="myscript">
var myscript=encodeURI(document.getElementById("myscript").innerHTML);
var msg="--this string is already URL encoded--";
/* Do some HTTP setting up here with XMLHttpRequest() object. */
send(httpcontent);
</script>
Since I plan on sending the script along with the already encoded message, I do not want to encode the message again. When I call encode() in the script above, it will encode everything within the script, including msg, which is already encoded. I want to just encode everything within the script tags, except what is within msg since it is already encoded.
So in this case, httpcontent will include both msg and myscript
Thanks

JQuery encodeURIComponent page not found error

I'm trying to encode my uri by using encodeURIComponent function. Here is my code.
//res[0].CLIENT_ID=10 and id=res[0].CLIENT_ID
var url = "new_quotation.php?clientid="+res[0].CLIENT_ID+"&quoteid="+id;
var encodedurl = encodeURIComponent(url);
$('#edit').attr("href", encodedurl);
It successfully encodes the uri, but when the page redirects it shows error as
The requested URL /Quotation/new_quotation.php?clientid=10&quoteid=0000000014 was not found on this server.
I saw the url. It seems like
http://localhost/Quotation/new_quotation.php%3Fclientid%3D10%26quoteid%3D0000000014
So, the uri is encoded but why not the page is redirected? Do I need to use any other function to redirect? Or is there any error in my code?
You should only be encoding the values, not the entire url.
var url = "new_quotation.php?clientid="+encodeURIComponent(res[0].CLIENT_ID)+"&quoteid="+encodeURIComponent(id);
$('#edit').attr("href", url);
Since you are using jQuery, you can also use param()
Each and every parameter in the URL must be applied encodeURIComponent (if the parameter consists of special characters)
Example :
var enc =param1+'/'+encodeURIComponent(param2)+'/'+encodeURIComponent(param3);
param2, param3 - here are expected to have special chars

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.
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.
var filtersParameter = 'filters=' + encodeURI(JSON.stringify(filters));
var filtersParameter = 'filters=' + atob(JSON.stringify(filters));
Note: atob() method uses base64 algorithm to encode the data. This encoded data can be easily passed to a server where it can be decoded using corresponding decoding methods (in python base64.b64decode(encoded_string) is used).

ASP.net MVC - Action Does not like JSON string 400 Bad Request

I have an action that takes 2 strings. One of the strings is a big, ugly json string. I suspect that the action will not allow the special characters to be passed because I keep getting a 400 - Bad Request.
Can a serialized json object be passed to an action?
public ActionResult SaveState(string file, string state)
{
string filePath = GetDpFilePath(file);
HtmlDocument htmlDocument = new HtmlDocument();
htmlDocument.Load(filePath);
HtmlNode stateScriptNode =
htmlDocument.DocumentNode.SelectSingleNode("/html/head/script[#id ='applicationState']");
stateScriptNode.InnerHtml = "var applicationStateJSON =" + state;
htmlDocument.Save(filePath);
return null;
}
ClientScript
'e' is a large json string
$.post('/State/SaveState/' + fileName+'/' + '/' + e + '/');
strong text
I am now encoding the text using UriEncoding() but it makes no difference. I don't think that MVC Actions allow me to send these special characters by default.. is that true? How do you work around this?
$.post('/State/SaveState/' + encodeURIComponent(fileName) + '/' + '/' + encodeURIComponent(e) + '/');
Sample request:
Request URL:http://localhost:51825/State/SaveState/aa6282.html//%7B%22uid%22%3A%22testUser%22%2C%22a
You need to encode it when the request is made:
$.post('/State/SaveState/' + encodeURIComponent(fileName) + '/' + encodeURIComponent(e));
Yes, serialized JSON object can be passed to an action method. MVC3 makes this even easier with built-in JSON binding. I use the json2 library to serialize the objects. See this post for more details. Works really great.
http://haacked.com/archive/2010/04/15/sending-json-to-an-asp-net-mvc-action-method-argument.aspx
Because I am send this data to the sever and the size of the string I am sending is large. I really should be sending the data in the post body.
It seems that there is also a limitation on the amount of data that you can send via the query string. I cannot be certain that this was the source of the error message but it certainly would make sense. In case the following post works correctly:
$.post('/State/SaveState/', { file: fileName, state: e });
You probably need to HTML-encode e before you add it to the URL. Also, you have an extra / that you don't need.

Categories

Resources