getting extra + while serializing - javascript

I am serializing form data with jquery serialize
var address = $('#formdata').serialize();
and then I do
decodeURIComponent(address);
so my address looks like this
1762+north+street
it decodes it but instead of spaces it adds + . What can I do (instead of of course replace + with space, bad solution) to decode it properly
thanks

Related

Sending URL request resulting in invalid JSON

I have this string with two variables inserted inside it
URL='https://bla.com/api/multicomplete?data={"query":"' + title_text + " " + city_name + '"}';
Sometime, title_text includes some wacky characters (&, $, letters like đ etc..) and it results in something like this:
title_text = 'Airport Hotel Park & Fly Sofia'
...?data={"query":"Airport%20Hotel%20Park%20&%20Fly%20Sofija",...
I can assume that that is because I have %20&%20 in URL, and indeed when I remove &%20 (& space), then I get no errors.
So I have tried this method:
JSON.stringfy(title_text)
to let me send those characters via URL, but it doesn't work. Is there a good method to escape those special characters in that long string? I don't feel like removing them for good, I feel so dirty thinking of it.
You have to use URI Encoding using encodeURI() to solve this problem.
You can do JSON.stringify and concatenate with the base url just like you've already done.

jQuery and JSON issue

I'm having an issue with the parser of jQuery when I give him a JSON string like this (java):
String JSONvalue = "[{"evaluationId":92688,"ResponseId":378501,"comment":"I can't do this ~!##$%^&*()_+|}{\":?><\/.,;'[]\\=-0987654321`","rankingId":0}]";
and when I pass it to the parser (javascript), it looks like this:
var prevCommentsAndRankings = jQuery.parseJSON('[{"evaluationId":92688,"ResponseId":378501,"comment":"I can't do this ~!##$%^&*()_+|}{\":?><\/.,;'[]\\=-0987654321`","rankingId":0}]');
I'm getting error of invalid tokens, this is because of the ' " and [ ] on the JSON string. How could I handle them, consider that the JSON may always have special characters within. Thanks in advance !
Just for the arbitrary strings replace the quote with it's HTML entity " BEFORE rendering it in JSON and right after you parsed the JSON. Both are common function you can find in Java and Javascript.

How to pass a hashtag in a ajax request

I have a chat that uses ajax to send messages to the server. My problem is that when the user tries to send a hashtag, everything after the hashtag is omitted. I saw a similar question like this that said encoding would help. I tried encoding it, but it created bigger problems when it got to the php. It started counting the + sign as a space and made the first two numbers after a % sign go missing. Is there a workaround to this in php, or should I try something other than encoding.
here is the relevant javascript with the encoding.
ajax.open("GET", "/chatAdd.php?msg=" + encodeURIComponent(message.value) + "&user=" + encodeURIComponent(user) + "&id=" + encodeURIComponent(id));
And the php i used to decode it.
$user = urldecode($_REQUEST["user"]);
$userID = urldecode($_REQUEST["id"]);
$msg = urldecode($_REQUEST["msg"]);
Use Percent encoding. Replace the hash with %23.
Edit: Also, a really great resource for escaping in JS and PHP - http://www.the-art-of-web.com/javascript/escape/

Converting textarea value into a valid JSON string

I am trying to make sure input from user is converted into a valid JSON string before submitted to server.
What I mean by 'Converting' is escaping characters such as '\n' and '"'.
Btw, I am taking user input from HTML textarea.
Converting user input to a valid JSON string is very important for me as it will be posted to the server and sent back to client in JSON format. (Invalid JSON string will make whole response invalid)
If User entered
Hello New World,
My Name is "Wonderful".
in HTML <textarea>,
var content = $("textarea").val();
content will contain new-line character and double quotes character.
It's not a problem for server and database to handle and store data.
My problem occurs when the server sends back the data posted by clients to them in JSON format as they were posted.
Let me clarify it further by giving some example of my server's response.
It's a JSON response and looks like this
{ "code": 0, "id": 1, "content": "USER_POSTED_CONTENT" }
If USER_POSTED_CONTENT contains new-line character '\n', double quotes or any characters that are must be escaped but not escaped, then it is no longer a valid JSON string and client's JavaScript engine cannot parse data.
So I am trying to make sure client is submitting valid JSON string.
This is what I came up with after doing some researches.
String.prototype.escapeForJson = function() {
return this
.replace(/\b/g, "")
.replace(/\f/g, "")
.replace(/\\/g, "\\")
.replace(/\"/g, "\\\"")
.replace(/\t/g, "\\t")
.replace(/\r/g, "\\r")
.replace(/\n/g, "\\n")
.replace(/\u2028/g, "\\u2028")
.replace(/\u2029/g, "\\u2029");
};
I use this function to escape all the characters that need to be escaped in order to create a valid JSON string.
var content = txt.val().escapeForJson();
$.ajax(
...
data:{ "content": content }
...
);
But then... it seems like str = JSON.stringify(str); does the same job!
However, after reading what JSON.stringify is really for, I am just confused. It says JSON.stringify is to convert JSON Object into string.
I am not really converting JSON Object to string.
So my question is...
Is it totally ok to use JSON.stringify to convert user input to valid JSON string object??
UPDATES:
JSON.stringify(content) worked good but it added double quotes in the beginning and in the end. And I had to manually remove it for my needs.
Yep, it is totally ok.
You do not need to re-invent what does exist already, and your code will be more useable for another developer.
EDIT:
You might want to use object instead a simple string because you would like to send some other information.
For example, you might want to send the content of another input which will be developed later.
You should not use stringify is the target browser is IE7 or lesser without adding json2.js.
I don't think JSON.stringify does what you need. Check the out the behavior when handling some of your cases:
JSON.stringify('\n\rhello\n')
*desired : "\\n\\rhello\\n"
*actual : "\n\rhello\n"
JSON.stringify('\b\rhello\n')
*desired : "\\rhello\\n"
*actual : "\b\rhello\n"
JSON.stringify('\b\f\b\f\b\f')
*desired : ""
*actual : ""\b\f\b\f\b\f""
The stringify function returns a valid JSON string. A valid JSON string does not require these characters to be escaped.
The question is... Do you just need valid JSON strings? Or do you need valid JSON strings AND escaped characters? If the former: use stringify, if the latter: use stringify, and then use your function on top of it.
Highly relevant: How to escape a JSON string containing newline characters using javascript?
Complexity. I don't know what say.
Take the urlencode function from your function list and kick it around a bit.
<?php
$textdata = $_POST['textdata'];
///// Try without this one line and json encoding tanks
$textdata = urlencode($textdata);
/******* textarea data slides into JSON string because JSON is designed to hold urlencoded strings ******/
$json_string = json_encode($textdata);
//////////// decode just for kicks and used decoded for the form
$mydata = json_decode($json_string, "true");
/// url decode
$mydata = urldecode($mydata['textdata']);
?>
<html>
<form action="" method="post">
<textarea name="textdata"><?php echo $mydata; ?></textarea>
<input type="submit">
</html>
Same thing can be done in Javascript to store textarea data in local storage. Again textarea will fail unless all the unix formatting is deal with. The answer is take urldecode/urlencode and kick it around.
I believe that urlencode on the server side will be a C wrapped function that iterates the char array once verses running a snippet of interpreted code.
The text area returned will be exactly what was entered with zero chance of upsetting a wyswyg editor or basic HTML5 textarea which could use a combination of HTML/CSS, DOS, Apple and Unix depending on what text is cut/pasted.
The down votes are hilarious and show an obvious lack of knowledge. You only need to ask yourself, if this data were file contents or some other array of lines, how would you pass this data in a URL? JSON.stringify is okay but url encoding works best in a client/server ajax.

Why mailto body does not recognize object literal as part of the url?

I have an object literal
var object = {
test: "test";
}
I call JSON.stringify on this object and append it to a query string
http://example.com?parameter={"test":"test"}
But when I append this query string into the mailto body, only this part
http://example.com?parameter=
got wrapped as an hyperlink while the rest is showed as plain text.
what I did was this:
window.location = "mailto:someone#example.com?subject=subject&body=http://example.com?parameter={"test":"test"}";
And when the email client view showed, only the part before '=' got wrapped as hyperlink.
The application that renders the emails just doesn't consider { as part of a url, you can try encoding it. It wont look pretty though.
Something like
window.location = 'mailto:someone#example.com?subject=subject&body=' + encodeURIComponent('http://example.com?parameter=' + encodeURIComponent('{"test":"test"}'));
This is actually related to accepted characters on URL. You should check this answer here: Characters allowed in a URL
So your link will work if you change this " to this ':
window.location = "mailto:someone#example.com?subject=subject&body=http://example.com?parameter={'test':'test'}";
Check out this Fiddle to replace quotation marks

Categories