i'm trying to pass a php defined string with spaces to a javascript function, so that i can append to a query string. However, the function only works when there are NO spaces, and does not even execute when there are spaces -- by testing with alert().
is there a way I can pass strings with spaces into javascript functions, so that i can eventually do an escape(), and then append to my query string? (using alert() in this example)
.php file
<a onClick=showUser('<?php echo $stringwithspaces; ?>')>click here</a>
.js file
function showUser(str)
{
alert (str);
}
if I could only do something like... onClick=showUser(escape('<?php echo $deptname; ?>'))... that would be awesome, but that didn't work. Any help would be much appreciated! Thanks!
The problem is you didn't quote the attribute value. You can leave quotes off of attribute values only if the value doesn't contain spaces, otherwise the HTML processor can't tell when an attribute ends. Even so, it's not recommended; you should always quote HTML attributes.
user
should work. The call to addslashes escapes quotes, which would otherwise cause another problem (ending the attribute or string argument of showUser too soon).
Yes you can you are missing " in you xml attribute field:
Each attribute must have a starting and an ending "
myField="blabla ..."
onClick="showUser(escape('<?php echo $deptname; ?>'))"
Try the Unicode escape sequence for a space character, '\u0020'.
Related
I am using AJAX to handle a form submission. The AJAX request returns a javascript script with text string arguments. I run into a problem when I try to add the AJAX returned script to the existing page.
Here are the different things I've tried to accomplish this already:
newAjaxBlock.appendChild(document.createTextNode(ajaxRequest.responseText));
newAjaxBlock.innerHTML = ajaxRequest.responseText;
newAjaxBlock.textContent = ajaxRequest.responseText;
The problem is that if I use .innerHTML to insert the returned script, it converts the escaped characters in the argument text string to their HTML equivalent and the script will throw errors because of single quotes and other characters in the string.
I expected .innerHTML to take the text and write it exactly as PHP provides it without unexpected conversions from escaped characters to their HTML equivalents.
For example I would generate a script in PHP and run it through htmlspecialchars() and make a text string exactly as follows:
<script type='text/javascript' id='layerScript'>Lib.alertFunction(arg1, $arg2, '<p>You changed THING from "value1" to "newValue".</p>');</script>
But instead .innerHTML converts it to this:
<script type='text/javascript' id='layerScript'>Lib.alertFunction(arg1, $arg2, '<p>You changed THING from "value1" to "newValue".</p>');</script>
and as you can see, the script won't work with single quotes and other characters messing up the argument list.
In contrast, when I tried using the createTextNode or .textContent options it creates a text node that ignores the HTML tags and shows it ALL as text instead of interpreting the HTML. This is not a surprise to me but leaves me with no option that actually just puts the HTML code in as it's written without converting the escaped characters.
All of the code works exactly as I expect and need it to except when the script argument contains single quotes or lt and gt symbols so I know I have narrowed the problem down to this single issue. I don't want jquery suggestions and I know I could code for an extra few days to make a function that does what I need but I want to know if there's something that does what .innerHTML does without converting escaped characters before I waste that time.
This exact question was already asked and was answered with "use .textContent" which as I mentioned doesn't work to insert formatted HTML with AJAX.
I have the below code in my JSP. UI displays every character correctly other than "&".
<c:out value="<script>var escapedData=unescape('${column}');
$('div').html(escapedData);</script>" escapeXml="false" /> </div>
E.g. 1) working case
input = ni!er#
Value in my escapedData variable is ni%21er%40. Now when I put it in my div using
$('div').html(escapedData); then o/p on html is as expected
E.g. 2) Issue case
input = nice&
Value in my escapedData variable is nice%26. Now when I put it in my div using
$('div').html(escapedData); then also it displays below
$('#test20').html('nice%26');
However, when output is displayed in JSP, it just prints "nice". It truncates everything after &.
Any suggestions?
It looks like you have some misunderstandings what unescape(val)/escape(val) do and where you need them. And what you need to take attention of when you use .html().
HTML and URI have certain character that have special meanings. The most important ones are:
HTML: <, >, &
URI: /,?,%,&
If you want to use one of those characters in HTML or URI you need to escape them.
The escaping for URI and for HTML are different.
The functions unescape/escape (deprecated) and decodeURI/endcodeURI are for URI. But was you want is to escape your data into the HTML format.
There is no build-in function in_JS_ that does this but you could e.g. use the code of the answer to this question Can I escape html special chars in javascript?.
But as it seems that you use jQuery you could think of just using .text instead of .html as this will do the escaping for you.
An additional note:
I'm pretty sure that the var escapedData=unescape('${column}'); does not do anything. I assume that ${column} already is ni!er#/nice&.
So please check your source code. If var escapedData=unescape('${column}'); will look like var escapedData=unescape('ni!er#'); then you should remove the unescape otherwise you would not get the expected result if the ${column} contains something like e.g. %23.
I am writing JavaScript templates for a content management system where users fill out text input fields that are passed to my templates.
My problem is the quotation marks in the input fields are not escaped before they are passed to my template, so I have no way of knowing if they will contain single or double quotes, or even both. Whichever way I try to handle the data my code ends up breaking because the quotes terminate the string declaration. I want to run a function on the data to escape quotes but I can't find a way to get the data into a valid variable first.
Is there any way to safely handle the data in JavaScript without it breaking a string variable declaration?
Edit: I'm posting code example;
CMS Text Input Field value is: Who'll win our "Big Contest"?
Text Input Field placeholder macro is [%TextInput%]
I'm building an HTML template for this input, using just JS/HTML/CSS
<script>
(function(){
var textInputStr = "[%TextInput%]";
})();
</script>
This will break the string declaration if the value of TextInput contains a single quote, and vice versa.
This is an awesome question, and one that deserves an answer. Strings in JS don't have a custom delimiter, like in most other modern languages, so you can get really stuck. But one solution is to build a script tag with the placeholder inside it, then find the innerHTML of that tag and grab the string back into a variable. eg
<script id="parseMe" type="text/template">
[%TextInput%]
</script>
then use
var yourString = document.getElementById("parseMe").innerHTML
Now you can manipulate the string as you please.
HTH!
I want to run a function on the data to escape quotes but I can't find a way to get the data into a valid variable first.
Well, you will have to make it a valid string literal before you could run JavaScript functions on it. There's no other way (unless you count an ajax request to the template script to get a string representation of it).
The input fields are not escaped before they are passed to my template
Then fix that. There's nothing you can do about it in JavaScript.
This url throws a missing ) after argument error. It is being dynamically generated by PHP. I cannot figure out the correct sequence/placement of single and double quotes to render it.
Cards
The particular effect desired is to onmouseover insert an image into .menu-image li. All I can figure out is that the img src with the quotes (I've tried single and double) is not liked and throws the argument error.
Try escaping the incorrect quotes with \ or \\.
I.e. html('<img src=\'cards_1.png\' />');
Alternatively, you can just use ". An URL encoder should have done this for you automatically.
A very popular error btw. is to not encode every & in an URL as &. Browsers usually guess right what was intended though, so people never learn. But the link
example
is actually incorrect and should be
example
Now if you had been using an URL encoder instead of just "printing" the string, it should automatically have converted your double quote to & and probably saved you some headaches.
Looks like you need to escape the innermost single quotes like so:
<a href="cards.html" onmouseover="jQuery('.menu-image li').html('<img src=\'cards_1.png\' />');
You need to write this:
Cards
...otherwise your browser can't distinguish if the apostrophes belong to the <img tag or the html( command
Use encoded quotes for the <img/> tag:
Cards
i have a long String. With some German characters and lots of new lines tabs ect..
In a Selectbox user can select a text, on change i do
document.getElementById('text').value=this.value;
But this fails. I just get a "unterminated string literal" as error in JavaScript.
I think i should clean the string.
How can i do it in JavaScript?
Its not because of that code, there is syntax error somewhere in your javascript file.
For example, in one of your previous question's answer
alert("yes link clicked);
You could see, there is " is missing after clicked, which could cause unterminated string literal error. Fix it like
alert("yes link clicked");
As I cannot judge from your code, you might want to check what this in this.value refers to, e.g. using an alert("debug: " + this.value) .
Other than that, you might want to use encodeURI() for converting umlauts and other special characters to hexadecimal notation. If your page's content-type is set to UTF-8 special characters will then display correctly.