I'm trying to implement some client side encoding/decoding onto a databind text box where data is passed between the tb and db.
What I have tried so far is server side functions with visual basic, however when the code is sent through I get an encoding error before the code's had a chance to run so it appears to me that JQuery/JS is the way to go to achieve this.
Can someone explain why it's unsafe to use htmlEncode and Decode like the below and how I need to go about stripping out the html using client side workarounds?
Thanks in advance.
function htmlEncode(value) {
return $('<div/>').text(value).html();
}
function htmlDecode(value) {
return $('<div/>').html(value).text();
}
The biggest problem of this approach is that it does not encode quotes, so if the input is used for an attribute value for example, it may break the html.
elem.innerHTML = '<div title="' + htmlEncode('" onhover="alert(1)') + '">X</div>';
will happily set the element to <div title="" onhover="alert(1)">X</div> and it can run the user's script then.
Related
I am currently using DYMO Label Printing software to print labels. I have previously had the label XML template stored as plain text and it worked fine. But recently I have decided to move to a more dynamic approach so that labels can be edited and modified directly from the database.
So I am currently storing the XML label templates in a simple SQL database table. I set up the viewmodel that contains the XML information, and then access it in Javascript when printing in the View itself.
I previously just tried this:
try {
var labelXml = "#Viewmodel.XMLString"; //Open XML from Viewmodel directly
var labelD = dymo.label.framework.openLabelXml(labelXml);
}
catch(err) {
alert("Couldn't load label");
return;
}
And that did not work.
I did some research and also tried this (placing viewmodel in "text/plain") and then accessing it above.
<script>
try {
var labelXml = $('#label_XML').text();
var labelD = dymo.label.framework.openLabelXml(labelXml);
}
catch(err) {
alert("Couldn't load label");
return;
}
</script>
<script id="label_XML" type="text/plain">
#Viewmodel.XML
</script>
Both of these methods result in this: (<> replaced with < and >)
How can I simply access a XML string in the database from the viewmodel while avoiding any unwanted conversions? Thanks.
Using #Html.Raw results in this problem:
The first line is read correctly but with each line break it reads as code instead of text. I put the original #Html.Raw in quotes, is there a way to prevent it from attempting to read it as code as shown above?
It looks like you are struggling with HTML Encoding. Have you tried using #Html.Raw(Viewmodel.XML)? That helper should prevent MVC from HTML encoding the content.
Depending on where that XML content comes from, you might be creating an XSS risk, so be careful how you use Html.Raw and consider reading more about it if it does solve this problem for you Is there a risk in using #Html.Raw?
When I receive html text by ajax in asp.net application it looks like:
<span%20style='color:green;font-weight:bold'>%20Text%20Msg</span>
how is it possible in javascript decode that text to normal html?
<span style='color:green;font-weight:bold'> Text Msg </span>
Thanks!
Nice function here that does it for you - http://phpjs.org/functions/htmlspecialchars_decode:427
You are probably best suited with finding a server side solution as already mentioned in the comments, since this seems like a server side problem.
If you for some reason wish to do this client side anyway, here is a solution:
var str = "<span%20style='color:green;font-weight:bold'>%20Text%20Msg</span>";
var fixedStr = decodeURIComponent(str).replace(/</g,'<').replace(/>/g,'>');
I'm trying to make a field similar to the facebook share box where you can enter a url and it gives you data about the page, title, pictures, etc. I have set up a server side service to get the html from the page as a string and am trying to just get the page title. I tried this:
function getLinkData(link) {
link = '/Home/GetStringFromURL?url=' + link;
$.ajax({
url: link,
success: function (data) {
$('#result').html($(data).find('title').html());
$('#result').fadeIn('slow');
}
});
}
which doesn't work, however the following does:
$(data).appendTo('#result')
var title = $('#result').find('title').html();
$('#result').html(title);
$('#result').fadeIn('slow');
but I don't want to write all the HTML to the page as in some case it redirects and does all sorts of nasty things. Any ideas?
Thanks
Ben
Try using filter rather than find:
$('#result').html($(data).filter('title').html());
To do this with jQuery, .filter is what you need (as lonesomeday pointed out):
$("#result").text($(data).filter("title").text());
However do not insert the HTML of the foreign document into your page. This will leave your site open to XSS attacks.
As has been pointed out, this depends on the browser's innerHTML implementation, so it does not work consistently.
Even better is to do all the relevant HTML processing on the server. Sending only the relevant information to your JS will make the client code vastly simpler and faster. You can whitelist safe/desired tags/attributes without ever worrying about dangerous ish getting sent to your users. Processing the HTML on the server will not slow down your site. Your language already has excellent HTML parsers, why not use them?.
When you place an entire HTML document into a jQuery object, all but the content of the <body> gets stripped away.
If all you need is the content of the <title>, you could try a simple regex:
var title = /<title>([^<]+)<\/title>/.exec(dat)[ 1 ];
alert(title);
Or using .split():
var title = dat.split( '<title>' )[1].split( '</title>' )[0];
alert(title);
The alternative is to look for the title yourself. Fortunately, unlike most parse your own html questions, finding the title is very easy because it doesn;t allow any nested elements. Look in the string for something like <title>(.*)</title> and you should be set.
(yes yes yes I know never use regex on html, but this is an exceptionally simple case)
I'm new to jQuery and to some extent JavaScript programming. I've successfully started to use jQuery for my Ajax calls however I'm stumped and I'm sure this is a newbie question but here goes.
I'm trying to return in an Ajax call a complete html structure, to the point a table structure. However what keeps happening is that jQuery either strips the html tags away and only inserts the deepest level of "text" or the special characters like <,>, etc get replaced with the escaped ones
I need to know how to turn off this processing of the received characters. Using firebug I see the responses going out of my WebServer correctly but the page received by the user and thus processed by jQuery are incorrect. A quick example will so what I mean.
I'm sending something like this
<results><table id="test"><tr>test</tr></table></results>
what shows up on my page if I do a page source view is this.
<results><table....
so you can see the special characters are getting converted and I don't know how to stop it.
The idea is for the <results></results> to be the xml tag and the text of that tag to be what gets placed into an existing <div> on my page.
Here is the JavaScript that I'm using to pull down the response and inserts:
$.post(url, params, function(data)
{
$('#queryresultsblock').text(data)
}, "html");
I've tried various options other than "html" like, "xml", "text" etc. They all do various things, the "html" gets me the closest so far.
The simplest way is just to return your raw HTML and use the html method of jQuery.
Your result:
<table id="test"><tr>test</tr></table>
Your Javascript call:
$.post(url, params, function(data){ $('#queryresultsblock').html(data) })
Another solution with less control — you can only do a GET request — but simpler is to use load:
$("#queryresultsblock").load(url);
If you must return your result in a results XML tag, you can try adding a jQuery selector to your load call:
$("#queryresultsblock").load(url + " #test");
You can't put unescaped HTML inside of XML. There are two options I see as good ways to go.
One way is to send escaped HTML in the XML, then have some JavaScript on the client side unescape that HTML. So you would send
<results><results><table....
And the javascript would convert the < to < and such.
The other option, and what I would do, is to use JSON instead of XML.
{'results': "<table id="test"><tr>test</tr></table>" }
The JavaScript should be able to extract that HTML structure as a string and insert it directly into your page without any sort of escaping or unescaping.
The other thing you could do is create an external .html file with just your HTML code snippet in it. So create include.html with
<results><table id="test"><tr>test</tr></table></results>
As the contents, then use a jquery .load function to get it onto the page. See it in action here.
I am a real noob when it comes to javascript/ajax, so any help will be very appreciated.
In reference to this question:
Updating a MySql database using PHP via an onClick javascript function
But mainly concerned with the answer left by Phill Sacre. I am wondering if someone could elaborate on how we are(if we can?) passing values/data through his example, using jquery.
The code example left by him is as follows:
function updateScore(answer, correct) {
if (answer == correct) {
$.post('updatescore.php');
}
}
...
<a onclick="updateScore(this, correct)" ...> </a>
Say for example, we are wanting to pass any number of values to the database with php, could someone give me a snippet example of what is required in the javascript function? Or elaborate on what is posted above please?
Thanks again all.
The simplest example I can think of is this. Make your AJAX call in your if block like this:
$.get('updatescore.php', {'score': '222'}, function(d) {
alert('Hello from PHP: ' + d);
});
On your "updatescore.php" script, just do that: update the score. And return a plain text stating wether the update operation was successful or not.
Good luck.
P.S.: You could also use POST instead of GET.
What you would do is on the php server side have a page lets say its update.php. This page will be visited by your javascript in an Ajax request, take the request and put it in a database.
The php might look something like this:
<?php
mysql_connect(...)
mysql_query("INSERT INTO table
(score) VALUES('$_GET["score"]') ")
Your javascript would simply preform an ajax request on update.php and send it the variables as get value "score".
Phil is not passing any values to the script. He's simply sending a request to the script which most likely contains logic to 'update' the score. A savvy person taking his test though could simply look at the HTML source and see the answer by checking to see what the anchor is doing.
To further nitpick about his solution, a set of radio buttons should be used, and within the form, a button or some sort of clickable element should be used to send the values to the server via an ajax request, and the values sent to the server can be analyzed and the status of the answer sent back to the page.
Since you're using jQuery, the code can be made unobtrusive as seen in the following example:
$('#submit_answer').click(function() {
var answer = 'blah' // With blah being the value of the radio button
$.get('updatescore.php',
{'value': answer},
function(d) {
alert('Your answer is: ' + d') // Where d is the string 'incorrect' or 'correct'
}
});
Enjoy.