I cant figure out why in ajax post "+" sign converts to " ".please explain ?
Use the encodeURIComponent() function to turn your data in valid encoded data for the request:
xhr.open("POST", url, true);
xhr.send(encodeURIComponent(postdata));
It's how URL encoding works. If you want a plus sign it's %2B, but you should really just escape or encode the data you're sending to the server. Type "a+b c" in here.
"+" is the url encoded symbol for space. As such, when your post data is decoded the "+" is converted to a space.
This is because URL Encoding converts spaces to + since spaces aren't valid in URLs.
Normally characters are converted to % followed by two hex digits, but having + instead of %20 makes URLs more readable.
If you encode your + as %2B that should work.
Chances are that you are using the + sign in an URL, where it is rightly converted into a space, as + is the URLEncoded representation of a space character.
Run escape() on whatever value you are putting into your URL to get it into URL-encoded form.
That's just standard url encoding. Plus signs are converted to spaces on the server. If you want to pass a plus sign you need to escape it as %2b.
Related
What is the difference between the JavaScript functions decodeURIComponent and decodeURI?
To explain the difference between these two let me explain the difference between encodeURI and encodeURIComponent.
The main difference is that:
The encodeURI function is intended for use on the full URI.
The encodeURIComponent function is intended to be used on .. well .. URI components that is
any part that lies between separators (; / ? : # & = + $ , #).
So, in encodeURIComponent these separators are encoded also because they are regarded as text and not special characters.
Now back to the difference between the decode functions, each function decodes strings generated by its corresponding encode counterpart taking care of the semantics of the special characters and their handling.
encodeURIComponent/decodeURIComponent() is almost always the pair you want to use, for concatenating together and splitting apart text strings in URI parts.
encodeURI in less common, and misleadingly named: it should really be called fixBrokenURI. It takes something that's nearly a URI, but has invalid characters such as spaces in it, and turns it into a real URI. It has a valid use in fixing up invalid URIs from user input, and it can also be used to turn an IRI (URI with bare Unicode characters in) into a plain URI (using %-escaped UTF-8 to encode the non-ASCII).
Where encodeURI should really be named fixBrokenURI(), decodeURI() could equally be called potentiallyBreakMyPreviouslyWorkingURI(). I can think of no valid use for it anywhere; avoid.
js> s = "http://www.example.com/string with + and ? and & and spaces";
http://www.example.com/string with + and ? and & and spaces
js> encodeURI(s)
http://www.example.com/string%20with%20+%20and%20?%20and%20&%20and%20spaces
js> encodeURIComponent(s)
http%3A%2F%2Fwww.example.com%2Fstring%20with%20%2B%20and%20%3F%20and%20%26%20and%20spaces
Looks like encodeURI produces a "safe" URI by encoding spaces and some other (e.g. nonprintable) characters, whereas encodeURIComponent additionally encodes the colon and slash and plus characters, and is meant to be used in query strings. The encoding of + and ? and & is of particular importance here, as these are special chars in query strings.
As I had the same question, but didn't find the answer here, I made some tests in order to figure out what the difference actually is.
I did this, since I need the encoding for something, which is not URL/URI related.
encodeURIComponent("A") returns "A", it does not encode "A" to "%41"
decodeURIComponent("%41") returns "A".
encodeURI("A") returns "A", it does not encode "A" to "%41"
decodeURI("%41") returns "A".
-That means both can decode alphanumeric characters, even though they did not encode them. However...
encodeURIComponent("&") returns "%26".
decodeURIComponent("%26") returns "&".
encodeURI("&") returns "&".
decodeURI("%26") returns "%26".
Even though encodeURIComponent does not encode all characters, decodeURIComponent can decode any value between %00 and %7F.
Note: It appears that if you try to decode a value above %7F (unless it's a unicode value), then your script will fail with an "URI error".
encodeURIComponent()
Converts the input into a URL-encoded
string
encodeURI()
URL-encodes the input, but
assumes a full URL is given, so
returns a valid URL by not encoding
the protocol (e.g. http://) and
host name (e.g.
www.stackoverflow.com).
decodeURIComponent() and decodeURI() are the opposite of the above
decodeURIComponent will decode URI special markers such as &, ?, #, etc, decodeURI will not.
encodeURIComponent
Not Escaped:
A-Z a-z 0-9 - _ . ! ~ * ' ( )
encodeURI()
Not Escaped:
A-Z a-z 0-9 ; , / ? : # & = + $ - _ . ! ~ * ' ( ) #
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/encodeURIComponent
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/encodeURI
Encode URI:
The encodeURI() method does not encodes:
, / ? : # & = + $ * #
Example
URI: https://my test.asp?name=ståle&car=saab
Encoded URI: https://my%20test.asp?name=st%C3%A5le&car=saab
Encode URI Component:
The encodeURIComponent() method also encodes:
, / ? : # & = + $ #
Example
URI: https://my test.asp?name=ståle&car=saab
Encoded URI: https%3A%2F%2Fmy%20test.asp%3Fname%3Dst%C3%A5le%26car%3Dsaab
For More: W3Schoools.com
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.
I have an application that takes text entered by a user and passes it to the server as part of a URL so that an image containing the text can be rendered. The URL parameter is encoded using encodeURIComponent function.
The problem I have is that if the user enters text containing + or foreign characters I cannot get the string decoded correctly server side.
For example, If the string is "François + Anna"
The encoded URL is previewImage.ashx?id=1&text=Fran%25E7ois%2520%2B%2520Anna
On the server
Uri.UnescapeDataString( Context.Request.QueryString["text"] )
Throws an "Invalid URI: There is an invalid sequence in the string." exception. If I replace the extended character from the string, it is decoded as "Francois + Anna"
However, if I use
HttpUtility.UrlDecode(
Context.Request.QueryString["text"], System.Text.UTF8Encoding.UTF7 )
the foreign characters are decoded correctly but the encoded + is changed to a space; "François Anna".
The URL wasn't encoded correctly to begin with. previewImage.ashx?id=1&text=Fran%25E7ois%2520%2B%2520Anna is not the correct URL encoding of François + Anna
I believe the correct encoding should have been previewImage.ashx?id=1&text=Fran%E7ois+%2B+Anna or previewImage.ashx?id=1&text=Fran%E7ois%20%2B%20Anna
Once the encoding has been fixed, then you should be able to retrieve the result via a simple Context.Request.QueryString["text"] call. No need to do anything special.
While passing my url, for example something:8000/something.jsp?param1=update¶m2=1000¶m3=SearchString%¶m4=3 , I am getting following error:
Bad Request
Your browser sent a request that this server could not understand.
I know SearchString% which I need to pass as a parameter, has the issue. Then how to pass a
parameter containing '%' in URL??
Use %25 in place of %
In URLs % has a special meaning as an escape character
Special characters like (space) can be encoded like %20 (the ascii code for space/32 in hex)
Therefore a percent sign itself must be encoded using the hex code for % which happens to be 25
You can use http://www.asciitable.com/ to look up the appropriate hex code under the hx column
Alternatively, if you are doing this programatically (ie. with javascript) you can use the builtin function escape() like escape('%')
See this: Encode URL in JavaScript?
Basically you need to make sure the variables you are passing are encoded (the '%' character is a special character in URL encoding).
Any special characters - %,?,&, etc... need to be encoded. They are encoded with '%' and their hex number. So '%' should become '%25', '&' becomes '%26', etc.
Update: see When are you supposed to use escape instead of encodeURI / encodeURIComponent? for why you should avoid using escape.
Using getJSON to retrieve some data which I am utf8 encoding on the server-side end...
"title":"new movie \u0091The Tree of Life\u0092 on day 6"
The page that is is displayed on is charset ISO-8859-1 and I am doing this...
$.getJSON('index.php', { q: q }, function(data){
for (var i = 0; i < data.length; i++) {
alert(data[i].title + "\n" + utf8_decode(data[i].title));
}
});
The utf8_decode function comes from here.
The problem is that I am still seeing the magic squares for both versions...
new movie The Tree of Life on day 6
new movie ᔨe Tree of Life⠯n day 6
This leads me to believe that perhaps the character is of neither encoding. However it works if I paste the string onto a page and set the charset to either UTF8 or ISO-8859-1 :-/
Any help would be great!
There is no need to escape or decode any characters in data transmitted in JSON. It's done automatically. It is also independent of the page's encoding. You can easily transmit and display the euro sign (\u20ac) with your code even though ISO-8859-1 does not contain the euro sign.
You problem are the characters \u0091 and \u0092. They aren't valid Unicode characters. They are for private use only.
It rather looks as if you in fact have data that originally used the Windows-1250 character set but was not properly translated to Unicode/JSON. In Windows-1250, these two characters are typographic single quotes.
Did you tried without utf8_decode ?
If the characters in your string exist in ISO-8859-1, this will just work, as Javascript decodes the \u0091 in the encoding of the page.