Sorry I couldn't be more descriptive with the title, I will elaborate fully below:
I have a web application that I want to implement some AJAX functionality into. Currently, it is running ASP.NET 3.5 with VB.NET codebehind. My current "problem" is I want to dynamically be able to populate a DIV when a user clicks an item on a list. The list item currently contains a HttpUtility.UrlEncode() (ASP.NET) string of the content that should appear in the DIV.
Example:
<li onclick="setFAQ('The+maximum+number+of+digits+a+patient+account+number+can+contain+is+ten+(10).');">
What is the maximum number of digits a patient account number can contain?</li>
I can decode the string partially with the JavaScript function unescape() but it does not fully decode the string. I would much rather pass the JavaScript function the faq ID then somehow pull the information from the database where it originates.
I am 99% sure it is impossible to call an ASP function from within a JavaScript function, so I am kind of stumped. I am kind of new to AJAX/ASP.NET so this is a learning experience for me.
First of all, if you're pulling the questions from the db on page load you most likely have all the answers too, so just keep going with your current approach by jamming the answers into the page as your code sample is doing. Unless your FAQ list has thousands and thousands of questions, doing it the "AJAX way" by hitting the db on each click of the list item doesn't give you much here IMO. If it does have that many questions then a straight list is the wrong way to go anyway.
Secondly, two things to keep in mind re your approach:
you're placing html inside an html attribute
the attribute is specifying a javascript function to call
So you need to make sure your "answer" escapes both html and is valid js. By valid js I mean it can't have new lines and must escape quotes properly. For example, the following html - although valid html - won't fire the onclick and you'd just get a js syntax error:
<li onclick="setFAQ('This line's
multi line and has a single quote in it!')"
To account for these I would say HttpUtility.HtmlAttributeEncode in tandem with System.Web.Script.Serialization.JavaScriptSerializer is more appropriate to the markup you've shown.
JavaScriptSerializer json = new JavaScriptSerializer();
string answerString = "This line's\nmulti line and has a single quote in it!";
string onClickJS = String.Format("setFAQ({0})", json.Serialize(answerString));
string onClickAttr = HttpUtility.HtmlAttributeEncode(onClickJs);
Even better, use .NET's ListItem object and lose HtmlAttributeEncode altogether:
ListItem faqItem = new ListItem(questionString);
faqItem.Attributes.Add("onclick", String.Format("setFAQ({0})", json.Serialize(answerString)));
The html portion is escaped automatically for you, plus it's a lot cleaner.
As for your javascript, you don't have to decode anything in setFAQ(). Just take its argument and put it in into you "answer" div:
function setFAQ(answer) {
document.getElementById('answer').innerHTML = answer
}
I think just using HttpUtility.HtmlEncode may solve your problem. I'm not sure I follow completely though : \
Related
I have an HTML page with a form. When a user fills the input field, I search the database for a match. A list is displayed with possible matches and can be clicked, the possible match will then be copied to the input field. All works well for "normal" text, but when a record contains an ' the possible match is not copied to the input field. Although in the PHP script I did an "addslashes", but it seems that I can't pass the value to the Javascript.
The PHP code is this:
$SafedbCheck = addslashes($dbCheck_result[1]);
<li class='CheckListItem' onClick='n0400AddResults_Click(<?php echo( $jsCheck)?>,"<?php echo( $SafedbCheck)?>")'><?php echo($dbCheck_result[1])?></li>
Which results in the following HTML lines:
<li class='CheckListItem' onClick='n0400AddResults_Click(1,"Gabe\'s Brand New Brand")'>Gabe's Brand New Brand</li>
and
<li class='CheckListItem' onClick='n0400AddResults_Click(1,"Gabrie")'>Gabrie</li>
For testing the Javascript function:
function n0400AddResults_Click( jsCheck, SearchItem )
{ alert( SearchItem ); }
Which works fine for the second line, but not for the first line even though the var I'm passing to the Javascript is slashed. Do I need to do some extra slashthingy?
You have three layers of code here.
Some data
Some JavaScript
Some HTML
Let's start with the data:
$jsCheck
You need to escape the data in a fashion suitable for inserting in the JavaScript.
In PHP, this is best done using the json_encode function which, despite the name, will convert any basic data structure into a JavaScript literal (not just objects and arrays).
Note that this will also add the appropriate quote characters so you should not include them yourself.
json_encode($jsCheck);
You then need to escape the data in a fashion suitable for inserting into the HTML.
In PHP, this is best done using the htmlspecialchars function.
htmlspecialchars(json_encode($jsCheck));
Putting this with the rest of your code gives you:
<li class="CheckListItem" onClick="n0400AddResults_Click(<?php echo htmlspecialchars(json_encode($jsCheck)); ?>,<?php htmlspecialchars(json_encode($SafedbCheck)?;>)">
That said, the approach has a couple of issues.
List items are not interactive items. The user will only be able to activate them using a mouse or other pointing device … and you have an anchor already (which is an interactive element).
onclick attributes are not unobtrusive
You'd probably be better off with something that stores the data in the URL you pass to the href attribute or, failing that, in data-* attributes and then binding a JavaScript event handler with addEventListener.
I have a table being built in HTML (using ASP), and it's stepping through a recordset. As it steps through the recordset, it creates a new row for the html table and fills it with data.
The problem I'm having is that it's using numbers that can be 10 or 11 digits long, and I want to format it with commas. I have a formatNumbers function that works excellently. However, basically what I need to do is this:
<td><script>formatNumber(<% = RS("total_rolled_lineal_ft")%>,0,0,true);</script></td>
I'm getting an Object Expected error. If we take a line from the executed HTML, here's what it looks like:
<td><script>formatNumber(10843537,0,0,true);</script></td>
Any clue what's causing my error, or, if I'm doing it completely wrong, how to fix it?
Also, formatNumber returns a string, in this case 10,843,537.
Thanks to #nnnnnn, I ended up using VB's FormatNumber() and came up with this
<% = FormatNumber(RS("total_rolled_lineal_ft"),0,true,true,true)%>, which works excellently.
I have never used straight ASP so maybe I am missing something in this answer.
Technically you can not execute Javascript while the ui is rendering, browsers tend to be a single threaded affair and will do one thing or the other.
But I would suggest that instead of binding the table directly to a record set you transform the record set into a ViewModel type class in the code behind.
You would then perform this conversion as you are building your ViewModel.
I have the server programmed in Cherrypy and I use also Mako Template.
And I have the variable dict (variable Mako that contain information's work) for working with the user( this I have to use Mako and JAvascript).
I have one problem that I can not pass the value's Mako to Javascript.
MAKO --->>> JAVASCRIPT and vicecersa Not can to pass.
When the user wants change the information, I need to use the form.
The information is for example the data is the identifying a person.
When I connect when the server localhost:8100 and I have in automatically dict on Url.
The user pushes the button's send.(submit) in case of change.
The server receipt the value in Javascript with the separator in Js and the old in MAko.
I have the problem for read and to convert the separator in Javascript.
It possible to change the string's submit's form While or before to sending?
I want to program the submit's form because I want to use the other delimiter(not & and =).
This is possible?
Now I write one example:
www.theuser.com/?Name=IBM&surname=PC
With if the function programmable while sending
www.thepc.com/?Name%24+IBM+%23%+Surname%24+PC
Repeat: when I sent the parameter, I not want this separator & or = and I want to use the others.
Separator
javascript Mako
= %24+
& +%23+
This Query String is the original for the my project:
http://localhost:8100/index2?json_data=demo_title%24+Demo+title+%23+proc1_script%24+script.sh+parameters+%23+proc1_chk_make%24+on+%23+outputp2_value%24++%23+demo_input_description%24+hola+mundo+%23+outputp4_visible%24+on+%23+outputp4_info%24++%23+inputdata1_max_pixels%24+1024000+%23+tag%24++%23+outputp1_id%24+nanana+%23+proc1_src_compresion%24+zip+%23+proc1_chk_cmake%24+off+%23+outputp3_description%24++%23+outputp3_value%24++%23+inputdata1_description%24+input+data+description+%23+inputp2_description%24+bien%3F+%23+inputp3_description%24+funciona+%23+proc1_cmake%24+-D+CMAKE_BUILD_TYPE%3Astring%3DRelease++%23+outputp2_visible%24+on+%23+outputp3_visible%24+on+%23+outputp1_type%24+header+%23+inputp1_type%24+text+%23+demo_params_description%24+va+bien+%23+outputp1_description%24++%23+inputdata1_type%24+image2d+%23+proc1_chk_script%24+off+%23+demo_result_description%24+win%3F+%23+outputp2_id%24+nanfdsvfa+%23+inputp1_description%24+funciona+%23+demo_wait_description%24+boh+%23+outputp4_description%24++%23+inputp2_type%24+integer+%23+inputp2_id%24+papapa+%23+outputp1_value%24++%23+outputp3_id%24+nananartrtrt+%23+inputp3_id%24+pepepe+%23+outputp3_type%24+header+%23+inputp3_visible%24++off+%23+outputp1_visible%24+on+%23+inputdata1_id%24+id_lsd+%23+outputp4_value%24++%23+inputp2_visible%24+on+%23+proc1_source%24+lsd-1.5.zip+%23+inputp3_value%24+si+%23+proc1_make%24+-j4+-C++%23+images_config_file%24+cfgmydemo.cfg+%23+outputp2_type%24+header+%23+proc1_subdir%24+xxx-1.5+%23+proc1_url%24+http%3A%2F%2Fwww.ipol.im%2Fpub%2Falgo%2F...+%23+inputdata1_image_depth%24+1x8i+%23+inputp1_id%24+popopo+%23+inputp1_value%24+si+%23+inputp2_value%24+no+%23+demo_data_filename%24+data_saved.cfg+%23+inputdata1_info%24+info_lsd+%23+outputp3_info%24++%23+inputdata1_image_format%24+.pgm+%23+outputp1_info%24++%23+inputdata1_compress%24+False+%23+inputp1_visible%24+on+%23+proc1_id%24+lsd+%23+outputp4_id%24+nana+%23+outputp2_description%24++%23+outputp4_type%24+header+%23+outputp2_info%24++%23+inputp3_type%24+float+%23+&tag=&inputp4_id=hi&inputp4_type=text&inputp4_description=hello+program&inputp4_value=no&inputp4_info=bol&inputp4_visible=on
For the moderator:
I read on the post https://stackoverflow.com/questions/13353539/how-to-change-how-the-url-is-encoded-when-a-form-is-submitted
But this was not interested in me.
P.s. The solution in Jquery or Javascript is equal for me.
Well I'm pretty sure your reasons for doing this don't justify doing it, but to answer the question, this is how you would change the tokens. I'm assuming jQuery, it's not entirely necessary but makes the code shorter.
HTML:
<form id="myform" action="myparser.php">
<input ...>
</form>
JavaScript:
$('#myform').submit(function(e){
e.preventDefault();
var q=$(this).attr('action'),f=this.elements,i;
for(i=0;i<f.length;++i){
q+=(i===0?'?':'+%23%+')+f[i].name+'%24'+f[i].value;
}
document.location.href=q;
return false;
});
That's slightly minified, so here's the gist. We begin by binding to the submit event, which we prevent (preventDefault and return false to be doubly sure), then get all the form's elements (this.elements) and iterate through them. By the end of the loop, q is a full URL which we want to submit to (using the action property and filling in all the names/values), so we just set the HREF to it and off we go. In this case to myparser.php.
Note that this does no character substitution whatsoever. You should make f[i].value safe in some way. From your question, it seems obvious that you don't want standard URL encoding, but you will need to do something to prevent bad characters being used.
Finally, this is just the sending side. You'll still need to do something clever on your server-side to actually read these values.
I am having a problem trying to resolve an apostrophe related issue.
I have searched SO, but could not find anything that would help me.
My clientside javascript code is:
var strUserText = uSettings.replace(/'/g, "'")
after the above line is executed, the form does a submit
document.form1.submit();
in code behind, a class retreives those values:
sUserSettings = request.form("strUserSettings ")
the result is a semi-truncated string.
Given the above code process flow, how can I save "John O'Brady's ASP Blog" in to a database?
I thought I was saving "John O'Brady's ASP Blog" but that isn't working.
Your question is quite vague. Why are you encoding the apostrophe? Is it breaking your output?
The best way to do it would be to submit your data AS-IS to the database... crappy JavaScript injection, apostrophe's, html markup, and all. Then you simply encode the output.
Server.HtmlEncode(strUserText)
Also, if you're using the latest version .NET, you can encode the output as follows
<%: strUserText %>
(assuming the strUserText string variable is set earlier in your view)
Under no circumstances should you ever take data input "as is" and insert it in a database; serious no-no. As regards the apostrophe - you can take a look at this solution:
calling stored procedure with apostrophe in argument doesn't work
Your question is vague but the above link should clue you into the fact that the solution lies in the way the SQL query is formulated. Above all else, you need to implement proper data validation/filtering of the input and encode it BEFORE inserting it in the database.
https://www.owasp.org/index.php/XSS_%28Cross_Site_Scripting%29_Prevention_Cheat_Sheet
don't do this:
var strUserText = uSettings.replace(/'/g, "'")
the reason is that HTML uses the "&" character to delimit query strings and form fields.
I suggest you POST your data AS IS, and handle the replace SERVER SIDE.
sUserSettings = request.form("strUserSettings ").Replace("'", "whatever")
Instead of Javascript function,when trying to save John O'Brady's ASP Blog into the database use:
Server.HTMLEncode("John O'Brady's ASP Blog")
result of above will be John O'Brady's ASP Blog
And when retrieving from the database and want to display it use
Server.HtmlDecode(NameField)
where NameField is the name of the column in the table.
this will result in John O'Brady's ASP Blog
I will first explain what I'm trying to do then I will explain why just in case you get bored of reading the whole scenario.
Basically I have some HTML markup stored in a variable I now need to a wait to access the different elements within the variable. For example:
var markUp = "<h3>h3 tag</h3><p>paragraph tag</p>";
What I need to know is if there is a way for me to query the variable to retrieve say the h3 tag, in a similar way you would use the query function ? I have seen some other practices where people append the var to a hidden div then query the div. I would prefer to avoid this but if that is the only way I will proceed.
I have come across this problem whilst developing a drag and drop application, on drop i use a custom creator function to change the items structure once it is dropped.
If further explanation is needed please say, thanks advance Jonathan
You can use dojo._toDom to create a DOM fragment from your string.
var markup = "<h3>h3 tag</h3><p>paragraph tag</p><p>another paragraph</p>";
var domFragment = dojo._toDom(markup);
dojo.query("p", domFragment).forEach(function(element,i) {
console.debug(element.innerHTML);
});
The underscore prefix in _toDom means that it's a "private" member method of dojo. Normally, it's bad practice to use these as if they were public (like I do here). However, in the case of _toDom I believe it's generally considered acceptable, and according to this trac entry, it sounds like it'll be made public in the next version.