Strings with double quotes in html input field displaying as &quot - javascript

Im getting data from sql and using php to generate javascript for an edit button for each entry. The edit interface uses a text input in a form. When the generated edit button is clicked, the text within this field is set to equal the name of the entry from sql.
This works fine in all cases expect when the name contains double quotes ("), in which case the quotes are replaced with &quot in the text field.
The php genertaed javascript is below:
function editButton($suffix,$name)
{
echo "<button class=\"edit\" onclick=\"editMode$suffix()\">Edit</button>";
echo "<script>
<!--
function editMode$suffix(){
document.getElementById(\"title\").innerHTML = \"Edit Artist\"
var main = document.getElementById(\"main\");
main.style.display = 'none';
var edit = document.getElementById(\"edit\");
edit.style.display = 'block';
//Set the input of the edit interface to be equal to the current name
document.getElementById(\"editInput\").value = \"$name\";
document.getElementById(\"artEdit\").value = \"$name\";
}
-->
</script>";
}
The $name variable is sanitized via htmlentities() before being passed to the function. Without doing so, the edit interface for entries with quotes will not even display.
I found this which sounds like the same issue but no solutions (https://code.google.com/archive/p/embeddedjavascript/issues/19) :/
IF anyone has a solution or can point out some stupid thing im doing thats causing this it would be very appreciated. At this point im going to have to just disable database entry for double quotes and limit to singles.

Just change all the double-quotes in the JavaScript portion to single-quotes, then use addslashes() on the $name variable:
function editButton($suffix, $name)
{
$name = addslashes( html_entity_decode($name) );
echo "<button class='edit' onclick='editMode$suffix()'>Edit</button>";
echo "<script>
<!--
function editMode$suffix() {
document.getElementById('title').innerHTML = 'Edit Artist'
var main = document.getElementById('main');
main.style.display = 'none';
var edit = document.getElementById('edit');
edit.style.display = 'block';
//Set the input of the edit interface to be equal to the current name
document.getElementById('editInput').value = '$name';
document.getElementById('artEdit').value = '$name';
}
-->
</script>";
}
*Also added html_entity_decode() to converts the entities back to their initial state. Consider removing the htmlentities() altogether, in which case, you can remove the html_entity_decode() from the above script.

Related

Formatting PHP text for use in Javascript variable

I am having a tough time covering all areas with special chars that could possibly break the variable in JavaScript. So for context I am pulling information from a database and then echoing it to JavaScript variable that will display the data which is text that has been entered by a user and stored to the table.
The php variable is $letter see the code below that I used to try to keep it from breaking
$letter = $order["letter"];
$letter = str_replace("'", "\'", $letter);
$letter = str_replace("\"", "\"", $letter);
$letter = str_replace("\r\n", "\\n",$letter);
Below is the line of code where I attempt to decode it so that it will display in an html format
$(".fa-eye").click(function () {
//clear pager html
$(".pager").html('');
$("#text-pager").html('<p class="text-left prevdescription"></p>');
//clear pager html
var parentTd = $(this).parent().parent('td');
var letterContent = parentTd.find('#letterTxt').val();
var pagerHtml = '<p class="controls"><a class="tp-control-arrow-left unactive"><span><</span></a><a class="tp-control-arrow-right"><span>></span></a><ul class="pager"></ul></p>';
$(".prevdescription").html(letterContent.replace(/\r?\n/g, '<br/>'));
It produces the output in the image below...what am I missing?
You may write me down in history\nWith your bitter, twisted lies,\nYou may tread me in the very dirt\nBut still, like dust, I\ ............. This is what it outputs. not showing all of the content.
Use json_encode(), it converts a PHP value to the equivalent JavaScript literal.
<script>
var letter = <?php echo json_encode($order['letter']); ?>;
</script>

If a parameter of event handler contains certain characters, JavaScript does not execute properly

php:
$str1 = "AAA\r\nBBBB\\CCC";
echo"<textarea id='aa1' onfocus='erase(\"".$str1."\", \"aa1\");'></textarea>";
$str2 = "AAABBBB\\CCC";
echo"<textarea id='aa2' onfocus='erase(\"".$str2."\", \"aa2\");'></textarea>";
$str3 = "AAABBBB\CCC";
echo"<textarea id='aa3' onfocus='erase(\"".$str3."\", \"aa3\");'></textarea>";
$str4 = "AAABBBBCCC";
echo"<textarea id='aa4' onfocus='erase(\"".$str4."\", \"aa4\");'></textarea>";
javascript:
function erase(str, id)
{
alert("good");
var field = document.getElementById(id);
if(field.value == str)
{
field.value = '';
}
}
If I click on textarea id='aa1', nothing happens.
If I click on textarea id='aa2' or textarea id='aa3', 'good' is printed but nothing happens to field.value.
If I click on textarea id='aa4', 'good' is printed and field.value is ''.
I want a string like AAA\r\nBBBB\\CCC to work like textarea id='aa4.
How can I do that?
I read the post below but it does not seem to help my situation:
Javascript parameter
Javascript Line Break Textarea
update:
I've replaced $str1 with json_encode($str1), So alert(); works fine now. (Thanks to Jordan Running.)
But the field.value part still does not work.
code refactoring is too hard in my situation... Is there any way to handle the field.value problem without code refactoring?
If quotes corrupt my HTML, I can putting $str1 in htmlspecialchars() and displaying it in <textarea>.
Generally speaking it's a bad idea to use string concatenation to build JavaScript. Your PHP code produces the following HTML:
<textarea id='aa1' onfocus='erase("AAA
BBBB\CCC", "aa1");'></textarea>
That's valid HTML, but the code in your onfocus attribute is not valid JavaScript. In JavaScript, you can't have a line break in the middle of a string literal. You can have a line break in a template literal (i.e. `one of these`), but that's not the right solution here.
A quick but short-sighted fix
When you need to "inject" some data into a block of JavaScript, you should always use json_encode:
$str1 = "AAA\r\nBBBB\\CCC";
echo "<textarea id='aa1' onfocus='erase(" . json_encode($str1) . ", \"aa1\");'></textarea>";
Make careful note of the quotation marks above. Because json_encode wraps strings in quotation marks, you don't need additional quotes around . json_encode($str1) ..
This will produce the following HTML:
<textarea id='aa1' onfocus='erase("AAA\r\nBBBB\\CCC", "aa1");'></textarea>
...whose onfocus handler works correctly, as you can see in this snippet:
function erase(...args) { console.log('erase called with', args); }
<textarea id='aa1' onfocus='erase("AAA\r\nBBBB\\CCC", "aa1");'></textarea>
A better way
The above is still fragile. What if your data has a ' in it? That'll break your HTML. The correct solution is to move your data out of the HTML entirely. Consider if you refactored your code to look something like this:
<textarea id="aa1"></textarea>
<textarea id="aa2"></textarea>
<textarea id="aa3"></textarea>
<textarea id="aa4"></textarea>
<?php
$erase_map = [
'aa1' => "AAA\r\nBBBB\\CCC",
'aa2' => "AAABBBB\\CCC",
'aa3' => "AAABBBB\CCC",
'aa4' => "AAABBBBCCC",
];
?>
<script>
const ERASE_MAP = <?php echo json_encode($erase_map); ?>;
function erase(event) {
if (event.target.value == ERASE_MAP[event.target.id]) {
event.target.value = '';
}
}
document.querySelectorAll('textarea').forEach(textarea => textarea.addEventListener('focus', erase));
</script>
In the above code, all of the data is in one place—a single associative array—instead of scattered around your HTML. It generates HTML code with a <script> tag into which the data is injected as a JSON object and assigned to a JavaScript variable:
<textarea id="aa1"></textarea>
<textarea id="aa2"></textarea>
<textarea id="aa3"></textarea>
<textarea id="aa4"></textarea>
<script>
const ERASE_MAP = {"aa1":"AAA\r\nBBBB\\CCC","aa2":"AAABBBB\\CCC","aa3":"AAABBBB\\CCC","aa4":"AAABBBBCCC"};
function erase(event) {
if (event.target.value == ERASE_MAP[event.target.id]) {
event.target.value = '';
}
}
document.querySelectorAll('textarea').forEach(textarea => textarea.addEventListener('focus', erase));
</script>

javascript adding to string not wokring

Im trying to get a link where I have to add a countrycode to a link.
Im trying this:
var link = "http://restcountries.eu/rest/v1/alpha?codes=" + myData;
Where myData is defined by:
var div = document.getElementById("dom-target");
var myData = div.textContent;
dom-target:
<div id="dom-target" style="display: none;">
<?php
$output = $_GET['id'];
echo htmlspecialchars($output);
?>
</div>
Where the $_GET['id'] is a code like FR or NL.
but for some reason when I console.log() it, it comes out with the link and underneath that I see the countrycode, indicating that it hasnt added the countrycode to the link.
Am I doing something wrong here?
var link = "http://restcountries.eu/rest/v1/alpha?codes=" + myData.trim();
the .trim() will remove and spaces
if that doesn't work you can try myData.replace(/(\r\n|\n|\r)/gm,""); this will remove line breaks.
good luck

Clear or Delete file from textField

I am working with PHP's Yii framework and having issues clearing or deleting the uploaded file from the textfield. Currently, it will delete the content from the fileField, but can't get it to delete the textfield. Any ideas?
UPDATE
I can now clear my textField because I've hard coded my clearFileInputField function by adding $('.getFile').val(""); I reference this in my HTML by adding the 'class' => 'getName' in the input section. While this clears the data, it doesn't remove the file after saving. Any suggestions?
HTML
<div id = "clearContent">
<?php echo $form->labelex($model,'info'); ?>
<?php echo $form->textfield($model,'info', array(placeholder => "No file chosen", readonly => true, 'class' => 'getName')); ?><br>
<?php echo $form->fileField($model,'info'); ?>
<?php echo $form->error($model,'info'); ?>
<input type="checkbox" onclick = "clearFileInputField('clearContent')" href="javascript:noAction();"> Remove File
</div>
JavaScript:
<script>
function clearFileInputField(tagId) {
document.getElementById(tagId).innerHTML = document.getElementById(tagId).innerHTML;
$('.getFile').val("");
}
</script>
I am not sure if I understood the problem you are having correctly. If I understood the question completely wrong, please elaborate and I will try to improve my answer.
If you want to remove the the content (the value attribute) of a text and file input you can use code like the following:
// listen to the click on the #clearnbtn element
document.getElementById('clearbtn').addEventListener('click', function() {
// Remove the value of the #foo and #bar elements
document.getElementById('foo').value = "";
document.getElementById('bar').value = "";
});
If you would like to remove an entire field you can do that like so:
// Retrieves the input element, gets its parents and removes itself from it
var fooElement = document.getElementById('foo');
fooElement.parentElement.removeChild(fooElement)
Or you can set the innerHTML attribute of the parent element to an empty string ('').
document.getElementById('clearContent').innerHTML = "";
https://jsfiddle.net/osjk7umh/1/

Hidden input value to php session

I have a form, which uses the following input towards the end:
<input type="hidden" id="ct_count" name="ct_count" value=""/>
The initialisation of the form is:
<form action="email_submission.php" method="post" id="form1" onsubmit="mySubmit();">
And the mySubmit function is:
function mySubmit() {
document.getElementById('ct_count').value = ct;
document.getElementById("form1").submit();
}
When i hit submit, I want to pass the value of ct, which is a variable count on the page, to email_submission.php and store it in a session variable. The session variable is returning blank on every submit, and i'm unsure if the value of the "ct" variable used is being passed through on the hidden field.
Is someone able to pick up where i'm going wrong? There are already variables stored correctly through this, so it's not my session settings as far as i know.
tldr: What's the correct way to take a javascript variable count and pass it through form submit to php?
EDIT:
this is the code for adding fields.
intiial loop for the variable "ct"
function new_link()
{
ct++;
<?php $ct = $ct + 1; ?>
document.getElementById("sec4_lender").setAttribute('name', 'sec4_lender_<?php echo $ct;?>');
document.getElementById("sec4_balance").setAttribute('name', 'sec4_balance_<?php echo $ct;?>');
document.getElementById("sec4_termdate").setAttribute('name', 'sec4_lender_<?php echo $ct;?>');
document.getElementById("sec4_security").setAttribute('name', 'sec4_security_<?php echo $ct;?>');
document.getElementById("sec4_description").setAttribute('name', 'sec4_description_<?php echo $ct;?>');
document.getElementById("sec4_status").setAttribute('name', 'sec4_status_<?php echo $ct;?>');
document.getElementById("sec4_repayment").setAttribute('name', 'sec4_repayment_<?php echo $ct;?>');
document.getElementById("sec4_repayment2").setAttribute('name', 'sec4_repayment_2_<?php echo $ct;?>');
var div1 = document.createElement('tr');
div1.id = 'sect4busloan_div_'+ct+'';
// link to delete extended form elements
var delLink = '<tr style="text-align:right;margin-right:65px">Del</tr>';
div1.innerHTML = document.getElementById('newlinktpl').innerHTML + delLink;
document.getElementById('newlink').appendChild(div1);
}
// function to delete the newly added set of elements
function delIt(eleId)
{
d = document;
var ele = d.getElementById(eleId);
var parentEle = d.getElementById('newlink');
parentEle.removeChild(parentEle.childNodes[eleId]);
var newct = ct - 1;
ct = newct;
<?php $ct = $ct - 1;?>
}
You're taking the input's value and always setting it to ct -
document.getElementById('ct_count').value = ct;
You should get a warning or error about ct in the console if you do it this. What you should do is set a variable to the value of the input -
var ct = document.getElementById('ct_count').value;
It also appears that you never set the value of the hidden field, so in the example I post here ct's value will always be blank.
It turned out that while bug testing i had moved that single session out of the conditionals for my script. So for every page other than the first i was moving on to, it was requesting a blank variable.
Idiocy at its finest. Thank you very much for everyone helping in this matter.

Categories

Resources