I have a condition below.
pop function in button input has line 1 followed by newline Line2.
When I click on button to javascript it pops error " Unexpected token ILLEGAL " in Console.
Value inside pop() of button is generated dynamically. I get this error only if I have a new line char in the input text.
<script type='text/javascript'>
function pop(valu)
{
alert("here"+valu);
document.getElementById('box').innnerHTML = valu;
}
</script>
<button onclick="pop('Line 1
Line 2')"> Click </button>
<textarea id='box'></textarea>
Backend is PHP.
Is there any way to achieve this on foreground ? or should I make any changes of inserting values to DB ?
I directly store the values in DB with newline character.
Solution is use to nl2br function in PHP side
nl2br($yournewlinestring);
function of PHP to convert newline to enter a new line for \n
But before storing convert your html line breaks in php like this
$_POST['xyz'] = preg_replace('/(?:\r\n|[\r\n])/', PHP_EOL, $_POST['xyz'] );
If you want the newline characters, just do something like:
<?php $pop_variable = str_replace("\n", '\n', $pop_variable); ?>
<button onclick='pop("<?php echo htmlentities($pop_variable, ENT_QUOTES) ?>")' />
Remember to also run htmlentities to escape the quotes.
I do think this is doing too much in HTML, though. It might be more beneficial to store this in a PHP array and then json_encode() it. That way you don't have to do the above or take into account what happens when a " or ' is in the $pop_variable and might also be expandable if you wanted to add more buttons (of course, this depends on your use case).
Example:
<script>
function pop(valu) {
// Should do some error checking to ensure pop_var is set
document.getElementById('box').innnerHTML = pop_var[valu];
}
var pop_var = <?php echo json_encode(['button1' => "Line 1\nLine2", 'button1' => "Another Line 1\nAnother line with ' single quotes..."]);
</script>
<button onclick="pop('button1')">Click</button>
<button onclick="pop('button2')">Click</button>
<textarea id='box'></textarea>
Related
echo "<button onClick='follow(".$name.");'></button>";
I need to pass a string as a parameter in follow(user) function onClick event jquery. But it's getting called as a value.
I tried kind of everything, but in php it looks a bit of a big deal for me. Is there any other way around to get the expected result as a string from a php variable.
You echo a php variable in javascript without adding quotes thus ending with a javascript variable name instead of a string.
Just add escaped quotes like this:
echo "<button onClick='follow(\"".$name."\");'></button>";
Quotes are off and if you're passing a string you need quotes wrapping the string in the function call.
There is various ways to do it, for standard " in html properties:
echo '<button onClick="follow(\''.$name.'\')"></button>';
echo "<button onClick=\"follow('".$name."')\"></button>";
echo "<button onClick=\"follow('$name')\"></button>";
for single quotes
echo '<button onClick=\'follow("'.$name.'")\'></button>';
echo "<button onClick='follow(\"".$name."\")'></button>";
echo "<button onClick='follow(\"$name\")'></button>";
But that's presuming your users are nice, a crafty user may create a username with \n in it, then from POSTing to storing and retrieving it would most likely be rendered as a new line:
<?php
$name = "Foo\nBar";
echo '<button onClick="follow(\''.$name.'\')"></button>';
Rendering the following which would cause the page to break:
<button onClick="follow('Foo
Bar')"></button>
Or worse a username like:
$name = "Foo')\"></button>\n<button onClick=\"window.location.href = ('http://example.com";
Which would render a stored XSS:
<button onClick="follow('Foo')"></button>
<button onClick="window.location.href = ('http://example.com')"></button>
So a better solution then to directly pass it in, would be to escape it, using htmlentities and json_encode so \n is not rendered by the html.
echo '<button onClick=\'follow('.json_encode(htmlentities($name, ENT_QUOTES, 'UTF-8')).')\'></button>';
Which would render to:
<button onClick='follow("Foo')"><\/button>\n<button onClick="window.location.href = ('http:\/\/example.com")'></button>
Though you should be validating usernames on create before allowing such an attack.
My site has some PHP generated content which echoes HTML elements. Some of these elements are responsive to javascript events...for one input element, the relevant event is onmouseout, but I can't seem to escape this properly.
$sql = mysqli_query($cxn, "SELECT stuff1, stuff2, stuff100, tags FROM myTable WHERE user_id = 'myID'");
while ($row = mysqli_fetch_assoc($sql)) {
$Tagstring = $row['tags'];
//lots of code
echo "<div class='myClass1 myClass2'>
<input type='text' name='myInput' value='".$Tagstring."' onmouseout='ajaxFunction(\"myString\", this.value.trim().replace(/,\s|\s,/g, ","))'>
</div>";
//more code
}
$Tagstring is a comma-separated string of text substrings. If a user edits his/her tags, I am trying to prevent the following:
$Tagstring = 'tag1,tag2'; //from database table
//User edits to 'tag1, tag2';
//Pointless ajax call and access of server, since if user input = original $Tagstring, this will return false as I have set up the ajax call, but if user input !== $Tagstring, then ajax function proceeds
I am not new to PHP and Javascript, so I know in PHP about str_replace or exploding the user input on "," and then trimming each member of the explode array. Alternatively, I could use Javascript to split on "," and then trim the pieces in a for loop (or something similar).
Can anyone tell me how to properly escape the following argument in my echoed function call?
this.value.trim().replace(/,\s|\s,/g, ",")
I tend to echo my output opposite of the way you have done it, which I feel is easier to control. Single quotes on the outside, and double quotes on the inside.
echo '<div class="myClass1 myClass2">
<input type="text" name="myInput" value="'.$TagString.'" onmouseout="ajaxFunction("myString", this.value.trim().replace(/,\s|\s,/g, ""))">
</div>';
What is the error you are seeing?
Fixed it...it seemed to be an escaping issue. This worked :
onmouseout='ajaxFunction(\"AStringNotAVariable\", this.value.trim().replace(/,\s|\s,/g, \",\"))'
whereas
//.replace(/,\s|\s,/g, ",") and .replace(/,\s|\s,/g, ',') and .replace(/,\s|\s,/g, \',\')
led to errors such as Uncaught SyntaxError: Unexpected token ILLEGAL
I use ckeditor in admin panel but in user submit form use simple textbox so user can input text and submit. Problem is when user enter text in textarea with Line Breaks it saves as it in SQL. I want to add BR after each line in sql.
For Example User Submits:
![F.R.I.E.N.D.S.:
(F)ight for you.
(R)espect you.
(I)nvolve you.
(E)ncourage you.
(N)eed you.
(D)eserve you and
(S)tand by you.][1]![SCREENSHOT oF DB SAVE][2]
got saved in DB as it with next line showing in output. But I want to save in DB as:
F.R.I.E.N.D.S.:<br />
(F)ight for you.<br />
(R)espect you.<br />
(I)nvolve you.<br />
(E)ncourage you.<br />
(N)eed you.<br />
(D)eserve you and<br />
(S)tand by you.
I use nl2br but its not working on user submit form If I use nl2br on admin processing form then on those fields already added with ckeditor it adds two BR tags.
Code used on user submit form is:
<textarea name="content" id="content" cols="60" rows="10" class="span7"><?php if(isset($content)) { echo $content; } ?></textarea>
$content = trim($_POST["content"])
$content = mysql_real_escape_string($content);
$content = nl2br($content);
No processing is used on admin approval form where ckeditor used on textarea. Text output from DB appears without Line Breaks in a single line in ckeditor.
if I use nl2br while output on this form it works but adds double BRs on earlier text posted through ckeditor.
also tried $content = preg_replace("/\r\n|\r/", "<br />", $content); as suggested by some one on stackoverflow on similar question
pls suggest me some function for this problem.
also suggest If I need to use some function like htmlentities or stripslashes to process content before Inserting into SQL.
Just replace the new line \r\n, \r first, then trim it.
$content = preg_replace("/\r\n|\r/", "<br />", $_POST["content"]);
$content = trim($content])
Or:
$content = nl2br($_POST["content"]);
$content = trim($content)
Good luck.
You need to use nl2br for displaying the value, whenever you need it, not for saving it.
I've seen numerous posts on how to do this either saying to use rawurlencode in the php and decodeURIComponent in javascript or just use json_encode. Neither work for me. Hoping someone can see what I'm doing wrong:
I have an html button like this:
<button id="editbutton" onClick='edit(this, "<?php echo htmlentities($_SERVER['REQUEST_URI']); ?>", "<?php echo $result_cameras[$i]["camera_type"]; ?>", "<?php echo rawurlencode($result_cameras[$i]["camera_name"]); ?>")'>Edit</button>
I pass that into the javascript edit button:
var edit = function(t, to, cameratype, cameraname, cameraquality, camerahash, camerastatus, emailnotice, camerasensitivity, axisuser, axispass, axisip, axisport)
{
if (mydiv.find("form").length) {
mydiv.show();
} else {
// fields
var $myform = $("<form id='EditCameraForm' name='' method='post' action='" + to + "'></form>");
var $myfieldset = $("<fieldset><legend>Edit camera settings</legend></fieldset>");
var $myinput = $('<input/>').attr('type','hidden').attr('name','camera_type').val(cameratype);
var $mylabel = $("<label for='CameraName'>Camera name: </label>");
var $myinput2 = js('<input/>').attr('size','25').attr('name','camera_name').attr('id','CameraName').val(decodeURIComponent(cameraname));
$myform.append($myinput, $mylabel, $myinput2);
...
}
...
}
I've tried using rawurlencode/decodeURIComponent as above and when I hit the edit button if the camera name is called: a"a (just testing the quotes) I get a"a. Backslashes such as a\b just returns some weird characters back.
If I try:
<?php echo json_encode($result_cameras[$i]["camera_name"]); ?>
and don't put anything in the javascript code I get this error:
missing ) after argument list
edit(this, "/dashboard", "WEBCAM", ""a"a"", "0", "3dd10c49784e2207de1e1932958bfb...
Where it is pointing to the ""a"a"".
Any suggestions?
You are in effect outputting a javascript string literal, so using htmlentities is not the correct thing to do. What you need instead is addslashes:
<?php echo addslashes($_SERVER['REQUEST_URI']); ?>
Edit: It goes without saying that you also need to do this for the other two strings you are echoing.
The reason this is correct is that the escape sequences for Javascript string literals are compatible with what addslashes does, if you ignore the fact that addslashes also escapes the "null" character. However, there's no way that character will be part of your URL so there is a perfect match between what addslashes does and what Javascript expects from its string literals.
For completeness I should mention that an appropriate usage of htmlentities is to process text that is being sent as part of HTML content; even then, htmlspecialchars (which performs a small subset of the work of htmlentities) is almost always the better fit.
rawurlencode() is for converting a string to an URL argument
htmlentities() is for converting a string to an HTML content
If you'd like to convert a string to a Javascript string it should be :
function f_str_2js($x) {
return str_replace( array("\n","\r","\t","'",'"') , array('\n','\r','\t',"\\'",'\"') , $x)
}
the above answers are correct, but you should consider to add your data to a php array or object, than jsonencode and add it to a date-attribute date-camera='{... than do eventbinding by using jQuery .on(.
This way you can access the data via $(this).data('camera'). It will be easy to extend you app without adding more and more parameters to the onclick-function.
for more information see:
http://api.jquery.com/jQuery.data/
http://api.jquery.com/on/
I'm trying to pass a parameter from php into my javascript function inside html. Is this at all possible? This is what I've got so far, but it seems to crash once it hits the condition:
$str="<input type='submit' value='-' onclick='Call(".$row['field1'].");'/>";
I hope that I won't have to find a work around for this.
Thanks.
EDIT:
This is the function that I'm trying to call
function Call(stuff)
{
alert(stuff);
$.get('reports.php',
{'param':'section', 'text':stuff},
function(returned_data)
{
alert(returned_data);
});
//alert('end');
}
And this is the function that I'm populating a table with.
function PopTable()
{
alert('end');
document.getElementById('table').innerHTML = 'Loading...';
$.get('reports.php',
{'param':'getstuff'},
function(returned_data)
{
document.getElementById('table').innerHTML = returned_data; // Clear the select
});
alert('end');
}
This is the php that I'm sending back population the table:
$str.= '<tr>';
$str.='<td bgcolor="#ffffff">' . $row['stuff'] .'</td>';
$str.='<td><input type='submit' value='-' onclick="Call('$row['stuff']');"/></td>';
$str.='</tr>'; //accumulate table
I can't seem to get a return value for Call(), and the alert doesn't even pop up
Try:
$str='<input type="submit" value="-" onclick="Call(\''.$row['field1'].'\');"/>';
I would bet you need quotes around the value if it is a string value
For example if $row['field1'] = 'test'; then:
Your version: <input type='submit' value='-' onclick='Call(test);'/> which would fail because test is not a valid variable
My Version <input type="submit" value="-" onclick="Call('test');"/> which would work becase 'test' is a string
What you're trying to do is possible, whereas it is not possible to pass a parameter from JavaScript into a PHP function.
When you say it crashes once it hits the condition, do you mean when you click on the input on the page? In that case, it's an error in your JavaScript syntax. I would try using Firebug with Firefox to track down the issue.
My first guess is there are no quotation marks inside the Call() method. So you're doing this:
Call(something)
and it should be like this:
Call('something')
This is possible, but I would be very careful about mixing PHP echos and javascript inline with strings because you need to escape javascript datatypes properly
In your example, $row['field1'] is probably from a database, so it's a string, so you need to surround the value with quotes in your javascript call. But that's not all, because what if there's a quote in your string, or a special character like a newline which needs to be escaped in javascript? And then what about html escaping?
A better approach is to import your javascript values in one place using json_encode(), then use your variables from there.
E.g.:
<?php
$jsonrow = json_encode($row);
?>
<script type="text/javascript">
var jsrow = <?=htmlspecialchars($jsonrow);?>;
</script>
<?php // some time later... ?>
<input type="submit" value="-" onclick="Call(jsrow.field1);" />