javascript - send ajax request without string concatenation - javascript

I have a page in wich the user will write a code (in a programming language). the code can be very long (more than 2000 characters) and can contain any type of characters. And when he press the send button the code will be sent (using javascript ajax) to a script file on the server etc..
currently i am using this to send the code with ajax :
jxobj.open('POST', 'www.my-website.com/my_script.php', true);
jxobj.send('code=' + code);
but if the code contains some characters like & then the value of code will be broken into many pieces and i can't retrieve it in my script file.
Is there any way to send ajax request without a string concatenation? I would like to use only javascript if possible and thanks.

The data format is well documented and the standard JavaScript encodeURIComponent function will encode data for it.
jxobj.send('code=' + encodeURIComponent(code));
Is there any way to send ajax request without a string concatenation?
Not really. The send method takes a string, so you have to build a string using some mechanism or another. You could achieve it with (for instance) arrays and joins, but it still comes down to the same basic principles.

Related

Server side JSON string validation

Is there a secure way to validate an incoming untrusted JSON string in php?
The client shows a dynamic form. The user can enter data into that form. The data needs to be saved on the server. The server will not work with the data, it will only pass it on to the client the next time the page is loaded in order to restore the forms values. Therefore I do not want to check every value separately and save it into its own database field.
I want to save it as a JSON string and insert it into the DOM as a object variable on every page load. Is there a secure way to sanitize the incoming JSON string for that?
If you're injecting the code into a script tag and you want to guarantee that it is pure Javascript code, without any potentially dangerous XSS vulnerabilities, the simple way would be to use PHP first to decode it and then to re-encode it.
$safeJSON = json_encode(json_decode($unsafeJSON));
Anything that is invalid JSON will return null when json_decode is called on it. In this case, the string "null" would be returned to your browser, which is unlikely to do any harm in this context!
It's worth noting, however, that what you are doing is only potentially unsafe because this is not actually JSON. When it's being used inside a script tag, it's simply a Javascript object literal. If you were using it as JSON, e.g. by doing an AJAX call, it would not be a security vulnerability because the browser will not recognise invalid JSON in a JSON.parse call. See this excellent blog post for more information on the difference between Javascript objects and JSON.

send unescaped string with XHR (javascript)

I have string containing javascript file content and I need to upload it to server (it's not part of server side code - it's used only for development (on-site code editing) process so security is not important). PHP script uses file and content variables. I found only implementations where xhr.send() argument was string in standard GET format (var1=sth&var2=sthelse) but I'd like to send this string without any encoding / decoding / escaping / unescaping on server side. As it's js it contains all possible characters including '&' or '='.
Is it possible to pass data to POST in other way than using standard query?
I'm rather not interested in jQ solution
Sending JS file contents in a query string parameter is not a good idea. A few points:
If your situation support HTML5 you can send files to your server with JS.
If you don't want to send as a file upload I would send it as POST data.
Any data encoded or escaped on the client can be decoded or unescaped on the server. In some setups this is automatically done for you. There's no reason to avoid this if it's the proper way to handle data.

Can one do a TRUE POST (? not var=val url type post) with AJAX XMLHttpRequest?

I wasnt quite sure how to ask this question, sorry.. but basically it's this..
I just started out w/ Ajax .. and with sending XMLhttpRequest in the background, i'm having problems w/ some html special characters in the form data , specially the & sign terminating the variable prematurely
eg. value "You & I" results to "You "
Now to explain this question from my perspective.. it's simply this.. if i submit my regular form using GET method, the same thing happens.. since the variables are URL-Encoded.. but if i set the form to POST method then everything is PRESERVED as i needed it..
Now I believe it has something to do w/ this (?)
hr.open("POST", link, true);
hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
particularly on the form-urlencoded part.. is there an alternative?
i'd hate to have to run a cleanup routine on each variable that i pass thru Ajax :(
the & sign terminating the variable prematurely
& is supposed to terminate values in x-www-form-urlencoded data. You need to encode your data when building URLs.
if i submit my regular form using GET method, the same thing happens.. since the variables are URL-Encoded
No. If you submit a regular form using GET, then the inputed data will be URL Encoded and ampersand characters that appear as data will be represented by %26 and not as raw & characters so the same thing won't happen.
is there an alternative [to application/x-www-form-urlencoded]?
You can use any data format you like. Some are easier to generate than others (JSON is particularly easy to generate from a browser). You then have the challenge of decoding them on the server (form handling libraries don't tend to do JSON, so you'd have to get the raw POST data and decode it yourself).
Since your actual problem is solved by encoding your data, this is unnecessary.

Flow of Jsp -> Javascript webpage (Ajax?)

I am making a website but I get a bit lost programming dynamic sites.
The user needs to enter x (inside a textbox), click submit, process in java (serverside) and present outcome as a report to the user (using javascript).
I'm at the moment using JSP to process the users input but now I need to pass the JSON code into the javascript. The javascript requires JSON data.
At the moment I have JSP which returns the necessary JSON code and the Javascript which works with hardcoded JSON code. I need to somehow store the returned JSON (from the JSP) in a variable and pass it to the Javascript. I have a vague understanding of AJAX - i'm just unsure if this is possible and how to link it all together.
Thank you.
Your JSP "page" can simply generate JSON directly. There's no reason the output from JSP has to be HTML. From the client, therefore, you POST to the server, the JSP runs, and the result (pure JSON from your JSP) is sent back to the client as the ajax response.
Sounds like the perfect place for AJAX - you can submit the request with javascript, and when it comes back process it further with javascript. Unless you want the page to refresh.
If you are using jQuery, you can look here to see how to implement it, should be relatively painless: http://api.jquery.com/jQuery.post/

Encoding user input as URL GET parameter in JavaScript

I'm writing a JavaScript function that needs to uphold three properties:
be very small and lightweight - no external libraries
encode a string in such a way as to be able to be passed as a GET parameter
this string must be decoded again at its destination
Effectively, it authenticates the user by sending his username and password to a PHP page which then verifies it. This is done via GET because I haven't yet found a way of doing a background cross-domain POST request. The trouble is that if the user has a character such as '#' or similar in his password, it doesn't get sent properly.
Currently to avoid this, I encode() the password string before sending it, which allows it to be received without problems. However, I read that PHP's urldecode() is not a perfect analog for this, as there are corner cases which are treated differently (i.e. ' ', '+', etc). Sadly I cannot find this document anymore, so I cannot quote it, but the gist was that one of them converts spaces into '+' signs, which the other treats as an actual plus sign, or something like that...
As such, I'm looking for a Javascript function that can take a string and make it URL-safe, and which has a perfect reversal function in PHP so that the original string can be recovered.
The arguably awful code I currently use to achieve this:
login.onsubmit = function(){
loginFailMsg.style.display = 'none';
var inputs = login.getElementsByTagName('input');
var formdata =
'username='+inputs[0].value+'&password='+encode(inputs[1].value);
submit.src = formtarget+'/auth/bklt?'+formdata;
userinfo = undefined;
setTimeout(getUserinfo,300);
return false;
};
encodeURIComponent, PHP will decode it automatically when populating $_POST or $_GET
'&password='+encode(inputs[1].value)
Where's encode function coming from? Seems to me the quick answer to your question is using encodeURIComponent() instead, available since JavaScript 1.5. See also Comparing escape(), encodeURI(), and encodeURIComponent(); it does not encode everything either, but does encode all the server expects it to.
(As for cross-domain AJAX POST calls, I'd really have a look at "JSON with Padding". See JSONP with jQuery that I mentioned in the comments earlier. This will also prevent issues with the timeout you've randomly chosen, and jQuery will also help you, a lot, to get rid of inputs[0].value and the like. And, as you apparently already have a MD5 hash on the server, I'd really hash the password client side as well --see Karl's answer-- and compare those hashes instead. Respect your user's password and your own time, drop that no external libraries requirement!)
I don't think there's such a thing as a reversible hash function. There are plenty of javascript md5 libraries available, however.

Categories

Resources