javascript: addContent - How to package - javascript

While making use of a sample for addContent (located at randomsnippets.com), I stumbled into a problem that I hope someone can help on. This may not be the best/only way to skin this cat, but we have a PHP/MySQL page that has to be modified to ADD rows for data entry when needed.
Their method works (please take a peak at their page), but the value for the FORM element TEXTAREA has it's own form elements in it, including TEXTAREA. The close of the latter TEXTAREA tag interrupts the first value and throws the remaining code to the page, not awaiting insertion by the Submit Button. Results Example: Click Here
The Submit button successfully produces the part that stayed inside, but you see the problem.
- Is there a way to use the javascript addContent function,
- Incorporate the utility of an ADD button
- But avoid using the packaging of FORMS?
Thanks for any help!
Bryan
p.s. The PHP is transparent. Direct inclusion of the HTML contained in the variable as the value of TEXTAREA produces the same result.

I don't really understand what you're trying to accomplish here, but it doesn't matter - the obvious problem is that you're including unescaped HTML in the textarea: the textarea's text must be escaped, just as you would escape text content anywhere else in a HTML document (converting < to < > to > & to &, etc.). The fact that you're ultimately feeding the text back through the browser's HTML parser doesn't matter - if you want the document to load properly, it has to be escaped:
Example:
desired content such as this:
<tr>
<td bgcolor="#F3F3F3" align="center" colspan="3"><hr size="1" color="#C0C0C0"></td>
</tr>
would be included in a textarea like so:
<textarea>
<tr>
<td bgcolor="#F3F3F3" align="center" colspan="3"><hr size="1" color="#C0C0C0"></td>
</tr>
</textarea>

Related

dynamically add row on click of fileupload showing file details

I want to populate the table dynamically with the filename, filesize and some operations like delete the file once the user selects the file to upload, showing details of the file selected to upload, in a table format using jsp, javascript or jquery. Please suggest.Thanks.
--EDITED--
I have tried the below code, but i'am not sure how to get the file size and perform delete operation without the upload has not yet performed.Whenever user choose the file the details of the file should be shown in the table below. Please find the similar scenario in http://jsfiddle.net/s98Tw/2/.
JSP code:
<table border="1">
<tr>
<th>SNo</th><th>FileName</th><th>FileSize</th><th>Action</th> </tr>
<tr><td><input type="text" name="sno" id="sno"/></td>
<td><input type="text" name="fileName" id="fileName"/></td>
<td><input type="text" name="fileSize" id="fileSize"/></td>
<td>Delete</input></td>
</tr>
</table>
JavaScript code:
function addFileData(field){
var file_name = document.getElementById("file1").value;
document.getElementById("fileName").value=file_name;
}
EDIT:
Here is a new DEMO
You should be able to take from that what you need. I didn't know what 'sno' was so I left it out, but it should be pretty similar to the other two!
You should look into window.File, window.FileReader, window.FileList, and window.Blob. Those objects will contain what you're looking for to gather information on a file before it is uploaded. The rest of the table manipulation is simple javascript code on the front end.
One good source might be this
OLD STUFF:
Despite the lack of detail, here is what I came up with... I hope it helps... DEMO
I would suggest that you look into the JQuery documentation for the .append() function. That is one way you can dynamically add an element to the DOM. Also, the .click() function is very useful for providing a way to bind an element to a click action such as a delete funciton, or a function to display details.
Please try to find your own understanding of these concepts before you copy and paste anything.
Also, Stack Overflow is meant to provide answers to 'practical, detailed questions.'. Please keep that in mind for the future.

Are HTML textbox value attributes safe from XSS attacks?

I have a textbox where I want to allow users the ability to type in potentially dangerous characters such as < and > (this is a mathematical expression data entry field which required me to disable ASP.NET validation on the textbox). The data is stored in a database and retrieved later for display on the page. When I display the data in the textbox, I am setting it like this:
textboxA.Text = expression; where expression comes from the database with the potentially dangerous characters.
Anyway, I tried purposely inserting something like < script>alert('hi') < /script> but I can't get this script to execute when the Text property is set (translates to value attribute in client-side HTML. The result looks like:
< input type="text" value="<script>alert('hi')< /script>">>< /input>
So what gives, is the value attribute safe from injections?
Note: The spaces before each tag in the examples is only for StackOverflow because it deletes tags from questions.
To properly insert this code into your site you must understand how your code work. I'm not sure how ASP.net declares input field but as long it doesn't automatically encode special characters then my tip should let you insert code.
If for example this is how code of your input looks like (this is input field for HTML site) where is <?php if (isset($_SESSION['username'])) {echo $_SESSION['username'];} ?> its part of the code that inserts your script back into the HTML page (assuming you are saving value into session and redisplay the value in the textbox)
If you're passing argument back to the form by using the URL:
http://www.website.com/index.php?username="><script>alert('hi')</script>
From
<input type="text" name="username"
value="<?php if (isset($_SESSION['username'])) {echo $_SESSION['username'];} ?>">
Then the code you want to inject must look like this:
"><script>alert('hi')</script>
Notice "> at the beginning of this code. Basically what it does is to end the value="" by using " tag and then closes input field with >.
So the actual result would be:
<input type="text" name="username" value=""><script>alert('hi')</script>
From there you will be able to insert code such as JavaScript.
The builtin textbox control automatically encodes the text attribute. When you checked the output, did you use view source or the developer console. The console shows escaped data as unescaped, while view source will show the actual output.
Anyways, a classical attack on textbox value attributes would be:
" autofocus onfocus="alert(1)

How to disable fields within a Javascript form

What is the best way of disabling(greying out) fields within a Javascript form? I have tried the disabled="disabled" on both the form and its fields but neither work e.g.:
<form:form id="testForm" method="post" disabled="disabled" action="${pageContext.request.contextPath}/testSave" commandName="testForm">
<tr>
<td valign="top" disabled="disabled">Name: </td>
<td valign="top"><form:input disabled="disabled" path="fName"/></td>
</tr>
</form:form>
Any ideas on what im doing wrong here?
Using JQuery you could do the following to disable all form fields for a given form:
$('#formId').find('input,select,textarea[,other elements]').prop('disabled', true);
Well, it sort of depends on exactly what you are trying to do.
The "sure fire" way of disabling form fields is a combination of "disabled" and "readonly" on the inputs. Between the two, you can cover everything that you could want:
grey out the input
make the input non-editable
make the input non-focasable
keep the input from being sent with the form
Since some browsers don't support the "greyed out" part of disabling, the best way to cover that is to set up a custom CSS to display disabled (or readonly) fields the way that you want them to show.
To get the right soluiton for what you want to do with your form, look here for the differences between the two attributes: http://kreotekdev.wordpress.com/2007/11/08/disabled-vs-readonly-form-fields/
Edit: Additionally, you might consider replacing the disabled inputs with text, if the data is not to be sent with the form . . . less confusing to the user than having an input field that they can't use.
See the below js sample; I hope my perception matches with your wish:
http://jsbin.com/avopuf/3/
Change css as per your requirement.
You can disable input tags, but not td
td tag attributes
Sounds like you can use a reference site to brush up on HTML. I find W3School to be a good starting point, it has tutorials and references for a variety of online technologies.
Specifically for HTML and HTML input tag
Also, how is it not working? (Is it not greying out, or user can still type in it, ...?)

Can't seem to change the h:outputText "value", or even the value expression, using JavaScript/jQuery

So here is my problem. I am trying to take the value that comes from the backend and get rid of unwanted text in the value. So basically I get a color back and there is an asterisk or two at the end of the color name. I send that value to a JavaScript function and remove any asterisks that may be present in the string. This has been working fine for me up until now. I found one other location that this was happening and when I try to do the same thing, it doesn't work. The string comes in with the asterisks, I remove them and replace the html with the new string and for a brief moment, it works, then the original string comes back.
So, here is a bit more detail. In the app I am working on, there is a link that when clicked opens a richfaces modal window. Then, there is a table that is populated with various quotes that have come in from the website. At the end of each row is a "View" link to view the details of the quote. When that is clicked, it opens another modal that has a table with each product, color, size, and other information they customer wants quoted on. In the "View" link code there is an onclick, this is where I put my function call.
<a4j:commandLink ajaxSingle="true" action="# editRequestedQuoteController.viewRequestedQuote}"
reRender="mainRequestedQuotePanel,subpanel,btnPanel,messagPanelView"
onclick="#{rich:component('viewRequestedQuotePanel')}.show(); changeColorName()">
<span>View</span>
<f:param name="orderId" value="#{order.id}"/>
</a4j:commandLink>
The changeColorName() function is called and runs the following code:
function changeColorName() {
jQuery(".managedorder-color-name").each(function(){
var existingColor = jQuery(this).text();
var newColor = existingColor.replace(/\*/g, '');
jQuery(this).text(newColor.trim(newColor));
});
}
The code newColor.trim(newColor) is just removing leading/trailing spaces from the string.
Here is the code where the string is being rendered:
<c:forEach var="orderItem" items="#{editRequestedQuoteBean.orderItems}" varStatus="status" >
...
<td rowspan="#{orderItem.logo.logoName != null ? '4' : '2'}">
<h:outputText styleClass="managedorder-color-name" value="#{orderItem.itemColor.swatchcolor}" />
</td>
...
</c:forEach>
When I debug it with FireBug, I can walk through the code and see it execute, so I know it is getting called. However I should point out here that sometimes on the first run through, the code does not seem to execute, but if I click the "veiw" link a second time then it does execute. When I step over the last line, I can see the text is replaced with the string I am sending, but then if I "continue" (F8), the string goes back to the version I started with, the one with the asterisks. Does anyone know why this might be happening? Please, anyone, let me know if this is unclear or if you need more information.
Thanks.
The changes are been overridden by the ajax rendering. The onclick is executed before the ajax request. But when the ajax request completes, then the HTML DOM tree is changed with new elements from the server side. You need to execute the changeColorName() JS function after the ajax rendering. You can use the oncomplete attribute for this.
<a4j:commandLink ... oncomplete="changeColorName()" />

Transfer possibly unsafe user input from hidden input field to DOM

The following is a simplified example of a page a user has created at a site (they created it by filling out a form and then they get a URL for the page; the below is the HTML for the page they created).
In the example, I'm taking the value of a hidden input field and then putting it into the DOM as is. That results in an alert, simulating an XSS attack.
What's the best way to prevent things like this? The value of #sourceinput was previously input by the same or a different user who's viewing the page below, and the user's input wasn't filtered to remove tags. (The actual case involves the jquery.tooltip.js plugin and it's bodyHandler callback; on mouseover a bodyHandler callback would get the hidden input and display it to the user.)
One way to deal with this would be to strip tags on input; I control what goes in the hidden textfield so that would seem to solve it.
Another way would be to strip tags in Javascript, but some of these don't seem to be 100% effective:
Strip HTML from Text JavaScript
Is there some sort of best practice that I'm missing, or are those two the best ways?
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<head>
<title></title>
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script>google.load("jquery", "1.7.1");</script>
<script>
$(document).ready(function() {
var badHTML = $('#sourceinput').val();
$('#destinationdiv').html( badHTML );
//$('#destinationdiv').text( badHTML );
});
</script>
</head>
<body>
<input type="hidden" id="sourceinput" value="<script>alert('hi');</script>" />
<div id="destinationdiv" style="width:10px;height:10px;background-color:red;"></div>
</body>
</html>
UPDATE: The solution I'm going with for now has three parts:
When the page the user has created is saved, I run PHP's strip_tags() on their input. These are just short text strings like titles and blurbs, so few users will expect they can enter HTML. That might not be appropriate for other situations.
When the page the user created is displayed, instead of putting what the user had entered in an input value attribute, I put their input inside a div.
I take the value out of that div using .text() (not .html() ). I then run that through the underscore function (see below).
Testing this out - including simulating skipping the first step - seems to work. At least I'm hoping there isn't something I missed.
Here's the escape function used by Underscore.js, if you don't want to use the entire Underscore library of functions:
var escape = function(string) {
return (''+string).replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"').replace(/'/g, ''').replace(/\//g,'/');
};
Used like
var safe_html = escape("<b>Potentially unsafe text</b>"); // "<b>hello</b>"
$("#destination").html(safe_html);
It's written well and is known to work, so I'd advise against rolling your own.
I would say what you commented out (using text() from jquery is the better option). That will make sure the text stays text which is what you want. Filtering or stripping may have unwanted side effects like removing a mathematical expression in the input (" x is < 5").
Do Nothing.
You are trying to protect the user from himself. There is no way the user A can harm user B. And for all you care, user A might as well type javascript:alert('hi') on the address bar and xss himself. And no matter what javascript escape function you create, a savvy user can always bypass it. All in all, its a pointless pursuit.
Now, if you start saving what the user entered on the server side, then you should definitely filter things. Don't build anything on your own. Depending on your server side language, there are several options. OWASP's AntiSammy is one such solution.
If you do choose to save user entered html on the server side, make sure to run it by antisammy or a similar library before saving it to the database. On the way out, you should simply dump the HTML without escaping, because you know whatever is in the database is sanitized.

Categories