How to initialize textarea content with some text - javascript

Writing an HTTP server in Ruby, I need to edit a file in the browser which uses certain source code (HTML, JavaScript and Ruby). I need to put any text file content in the value of a textarea:
"<textarea>__CONTENT__</textarea>".gsub('__CONTENT__',File.read(filename))
However, this doesn't work if the files contain some special sub-trings, such as </textarea>. So I tried to 'prepare' the data, by doing certain replacements in the file content. However, there is an issue if the file contains source code with HTML/Ruby content, and especially if I try to send the source of my HTTP server. This chain of replacements seem good:
File.read(__FILE__).gsub(/&/,"&").gsub('<',"&"+"lt;").gsub('>',"&"+"gt;")
However, this is not good enough. There is an issue (in the web browser) when the file contains \'! Is there a useful technique to place any text in the textarea (server side and/or browser side)?

CGI::escapeHTML will "prepare" strings to be HTML-safe.
# require 'cgi'
CGI::escapeHTML(File.read(__FILE__))

this form is good:
CGI::escapeHTML(File.read(FILE))
except for the backslash character : double backslash become simple.
I found that :
Server side, replace backslash with &99992;
CGI::escapeHTML(File.read(#uri).gsub('\\','&9999'+'2222;'))
Browser side, replace in textarea "&99992222;" by backslash character :
var node=document.getElementById('textarea_1');
node.value=node.value.replace(/\&9{4,4}2{4,4};/g,String.fromCharCode(92));
Hopping that there is no sources with &99992222; !

Related

Newline characters disappear after uploading a txt to a server

Can't parse any data from a txt file (not a csv for a reason) when it's uploaded to a server because all the newline characters a apparently gone. d3.js parser that I'm using parseRows does not work properly without them.
On a localserver everything seems to be fine.
d3.text('fileName.txt', 'text/plain', function(fileContent) {
console.log(/\n/.test(fileContent));
});
[localserver]: true
[onlineserver]: false
Using free hosting on Hostinger, Apache server according to Wappalyzer. Don't know much about it.
Tried different encodings. No luck.
Update:
I downloaded the txt back from the server and opened it in Sublime Text. No newline characters in it. The exact local copy is fine.
Solved by avoiding: Decided to save some time and nerve and uploaded my txts to Dropbox. In case someone has same problems, here is a little trick to get direct links to Dropbox files http://techapple.net/2014/04/trick-obtain-direct-download-links-dropbox-files-dropbox-direct-link-maker-tool-cloudlinker/
Also solved by berserking: Changing the extension of the file (to csv for example) also helps, lol
Your server is probably trying to sanitize the strings it receives from the UI in order to prevent things like cross-site attacks.
Trying to escape the string you send to the server with encodeUri(str) and if you need to decodeUri(decodedStr)

special characters in title tag

How do you enter special characters in the title attribute of html?
My JavaScript code:
var link_english = document.createElement("img");
link_english.setAttribute("src", "images/english_out.png");
link_english.setAttribute("title", "The english version of Nauma.com"); //
link_english.className = "classEnglish";
My question is: How do I insert a special tag within the value of the title attribute?
Example:
link_english.setAttribute("title", "here I want to put a special character for a German letter, the " ü " ");
If it is a normal html file, no problem.
Just enter them.
You only need to ensure that the HTML page is saved using a character encoding which supports those characters (UTF-8 is preferred if you want world domination) and that the HTML page is been served over HTTP with a Content-Type header which signifies the very same character encoding, so that the browser understands how to display them to the human, e.g text/html;charset=UTF-8.
How to save the files the right way depends on the editor used, but usually this is available by Save As function and/or in the general editor settings. How to set the right HTTP content type header depends on the programming language and/or webserver used.
Update: the above answer still applies on your update. Save/serve file as UTF-8 and instruct browser by Content-Type header to interpret it as UTF-8. This applies on JS files as good as on HTML files and other text based files.
Yes you can but to enter special character you have to use its HTML entity. Here is the table for special characters and its HTML entity.

How can I access the data from javascript by Qt?

I used webview to show the webpage,
view->setUrl(QUrl("C:\\Qt\\2010.07\\qt\\serbest\\googleSearch.htm"));
in the HTML code I put some ajax code googleSearch. After I execute the program, the webview runs and there are results (pages links).
When I clicked any of the links they do not open. So what do I do to open the links I clicked?
How can I access the title of the links from the result of javascript in Qt?
"C:\Qt\2010.07\qt\serbest\googleSearch.htm"
That's not a URL, it's a Windows pathname. Also, it has troublesome unescaped backslashes: \201 is a string literal escape for the control character U+0081 in many languages (including JavaScript as per your tags, though the snippet does not appear to actually be JavaScript).
The URL form of that filename would look something like:
"file:///C|/Qt/2010.07/qt/serbest/googleSearch.htm"
You can convert a filename into a URL using fromLocalFile().

iPhone browser/IIS/Tomcat, Japanese locale, http parameters getting messed

First the environment: the client is a mobile Safari on iPhone, the server consists of a Tomcat 5.5 fronted by IIS.
I have a piece of javascript code that sends a single parameter to the server and gets back some response:
var url = "/abc/ABCServlet";
var paramsString = "name=SomeName"
xmlhttpobj = getXmlHttpObject(); //Browser specific object returned
xmlhttpobj.onreadystatechange = callbackFunction;
xmlhttpobj.open("GET", url + "?" + paramsString, true);
xmlhttpobj.send(null);
This works fine when the iPhone language/locale is EN/US; but when the locale/language is changed to Japanese the query parameter received by the server becomes "SomeName#" without the quotes. Somehow a # is getting appended at the end.
Any clues why?
Hopefully, all you need to do is add a meta tag to the top of your HTML page that specifies the correct character set (e.g. <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />) and match whatever encoding your datafiles are expecting.
If that doesn't work, ensure that you are using the same character encoding (preferably UTF-8) throughout your application. Your server-side scripts and any files that include text strings you will be adding directly to the response stream should be saved with that single encoding. It's a good idea to have your servers send a "Content-Type" HTTP header of the same encoding if possible (e.g. "text/html; charset=utf-8"). And you should ensure that the mobile safari page that's doing the displaying has the right Content-Type meta tag.
Japanese developers have a nasty habit of storing files in EUC or ISO-2022-JP, both of which often force the browser to use different fonts faces on some browsers and can seriously break your page if the browser is expecting a Roman charset. The good news is that if you're forced to use one of the Japanese encodings, that encoding will typically display right for most English text. It's the extended characters you need to look out for.
Now I may be wrong, but I THOUGHT that loading these files via AJAX was not a problem (I think the browser remaps the character data according to the character set for every text file it loads), but as you start mixing document encodings in a single file (and especially in your document body), bad things can happen. Maybe mobile safari requires the same encoding for both HTML files and AJAX files. I hope not. That would be ugly.

Having encoded a unicode string in javascript, how can I decode it in Python?

Platform: App Engine
Framework: webapp / CGI / WSGI
On my client side (JS), I construct a URL by concatenating a URL with an unicode string:
http://www.foo.com/地震
then I call encodeURI to get
http://www.foo.com/%E5%9C%B0%E9%9C%87
and I put this in a HTML form value.
The form gets submitted to PayPal, where I've set the encoding to 'utf-8'.
PayPal then (through IPN) makes a post request on the said URL.
On my server side, WSGIApplication tries to extract the unicode string using a regular expression I've defined:
(r'/paypal-listener/(.+?)', c.PayPalIPNListener)
I'd try to decode it by calling
query = unquote_plus(query).decode('utf-8')
(or a variation) but I'd get the error
/paypal-listener/%E5%9C%B0%E9%9C%87
... (ommited) ...
'ascii' codec can't encode characters
in position 0-1: ordinal not in
range(128)
(the first line is the request URL)
When I check the length of query, python says it has length 18, which suggests to me that '%E5%9C%B0%E9%9C%87' has not been encoded in anyway.
In principle this should work:
>>> urllib.unquote_plus('http://www.foo.com/%E5%9C%B0%E9%9C%87').decode('utf-8')
u'http://www.foo.com/\u5730\u9707'
However, note that:
unquote_plus is for application/x-form-www-urlencoded data such as POSTed forms and query string parameters. In the path part of a URL, + means a literal plus sign, not space, so you should use plain unquote here.
You shouldn't generally unquote a whole URL. Characters that have special meaning in a component of the URL will be lost. You should split the URL into parts, get the single pathname component (%E5%9C%B0%E9%9C%87) that you are interested in, and then unquote it.
(If you want to fully convert a URI to an IRI like http://www.foo.com/地震 things are a bit more complicated. Only the path/query/fragment part of an IRI is UTF-8-%-encoded; the domain name is mapped between Unicode and bytes using the oddball ‘Punycode’ IDN scheme.)
This gets received in my python server side.
What exactly is your server-side? Server, gateway, framework? And how are you getting the url variable?
You appear to be getting a UnicodeEncodeError, which is about unexpected non-ASCII characters in the input to the unquote function, not an decoding problem at all. So I suggest that something has already decoded the path part of your URL to a Unicode string of some sort. Let's see the repr of that variable!
There are unfortunately a number of serious problems with several web servers that makes using Unicode in the pathname part of a URL very unreliable, not just in Python but generally.
The main problem is that the PATH_INFO variable is defined (by the CGI specification, and subsequently by WSGI) to be pre-decoded. This is a dreadful mistake partly because of issue (1) above, which means you can't get %2F in a path part, but more seriously because decoding a %-sequence introduces a Unicode decode step that is out of the hands of the application. Server environments differ greatly in how non-ASCII %-escapes in the URL are handled, and it is often impossible to recreate the exact sequence of bytes that the web browser passed in.
IIS is a particular problem in that it will try to parse the URL path as UTF-8 by default, falling back to the wildly-unreliable system default codepage (eg. cp1252 on a Western Windows install) if the path isn't a valid UTF-8 sequence, but without telling you. You are then likely to have fairly severe problems trying to read any non-ASCII characters in PATH_INFO out of the environment variables map, because Windows envvars are Unicode but are accessed by Python 2 and many others as bytes in the system codepage.
Apache mitigates the problem by providing an extra non-standard environ REQUEST_URI that holds the original, completely undecoded URL submitted by the browser, which is easy to handle manually. However if you are using URL rewriting or error documents, that unmapped URL may not match what you thought it was going to be.
Some frameworks attempt to fix up these problems, with varying degrees of success. WSGI 1.1 is expected to make a stab at standardising this, but in the meantime the practical position we're left in is that Unicode paths won't work everywhere, and hacks to try to fix it on one server will typically break it on another.
You can always use URL rewriting to convert a Unicode path into a Unicode query parameter. Since the QUERY_STRING environ variable is not decoded outside of the application, it is much easier to handle predictably.
Assuming the HTML page is encoded in utf-8, it should just be a simple path.decode('utf-8') if the framework decodes the URLs percentage escapes.
If it doesn't, you could use:
urllib.unquote(path).decode('utf-8') if the URL is http://www.foo.com/地震
urllib.unquote_plus(path).decode('utf-8') if you're talking about a parameter sent via AJAX or in an HTML <form>
(see http://docs.python.org/library/urllib.html#urllib.unquote)
EDIT: Please supply us with the following information if you're still having problems to help us track this problem down:
Which web framework you're using inside of google app engine, e.g. Django, WebOb, CGI etc
How you're getting the URL in your app (please add a short code sample if you can)
repr(url) of when you add http://www.foo.com/地震 as the URL
Try adding this as the URL and post repr(url) so we can make sure the server isn't decoding the characters as either latin-1 or Windows-1252:
http://foo.com/¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖ×ØÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõö÷øùúûüýþÿ
EDIT 2: Seeing as it's an actual URL (and not in the query section i.e. not http://www.foo.com/?param=%E5%9C%B0%E9%9C%87), doing
query = unquote(query.encode('ascii')).decode('utf-8')
is probably safe. It should be unquote and not unquote_plus if you're decoding the actual URL though. I don't know why google passes the URL as a unicode object but I doubt the actual URL passed to the app would be decoded using windows-1252 etc. I was a bit concerned as I thought it was decoding the query incorrectly (i.e. the parameters passed to GET or POST) but it doesn't seem to be doing that by the looks of it.
Usually there is a function in server-side languages to decode urls, there might be one in Python as well. You can also use the decodeURIComponent() function of javascript in your case.
urllib.unquote() doesn't like unicode-string in this case. Pass it byte-string and decode afterwards to get unicode.
This works:
>>> u = u'http://www.foo.com/%E5%9C%B0%E9%9C%87'
>>> print urllib.unquote(u.encode('ascii'))
http://www.foo.com/地震
>>> print urllib.unquote(u.encode('ascii')).decode('utf-8')
http://www.foo.com/地震
This doesn't (see also urllib.unquote decodes percent-escapes with Latin-1):
>>> print urllib.unquote(u)
http://www.foo.com/å °é
Decoding string that already unicode doesn't work:
>>> print urllib.unquote(u).decode('utf-8')
Traceback (most recent call last):
File "<input>", line 1, in <module>
File ".../lib/python2.6/encodings/utf_8.py", line
16, in decode
return codecs.utf_8_decode(input, errors, True)
UnicodeEncodeError: 'ascii' codec can't encode characters in position 19-24: o
rdinal not in range(128)
check out this way
var uri = "https://rasamarasa.com/service/catering/ගාල්ල-Galle";
var uri_enc = encodeURIComponent(uri);
var uri_dec = decodeURIComponent(uri_enc);
var res = "Encoded URI: " + uri_enc + "<br>" + "Decoded URI: " + uri_dec;
document.getElementById("demo").innerHTML = res;
for more check this link
https://www.w3schools.com/jsref/jsref_decodeuricomponent.asp
aaaah, the dreaded
'ascii' codec can't encode characters in position... ordinal not in range
error. unavoidable when dealing with languages like Japanese in python...
this is not a url encode/decode issue in this case. your data is most likely already decoded and ready to go.
i would try getting rid of the call to 'decode' and see what happens. if you get garbage but no error it probably means people are sending you data in one of the other lovely japanese specific encodings: eucjp, iso-2022-jp, shift-jis, or perhaps even the elusive iso-2022-jp-ext which is nowadays only rarely spotted in the wild. this latter case seems pretty unlikely though.
edit: id also take a look at this for reference:
What is the difference between encode/decode?

Categories

Resources