Hello i have a script php and javascript, i want call my function javascript from php, but i have a problem when my string have a new line, when i turn firebug in firefox
this error is
"SyntaxError: unterminated string literal"
This is my code
<script>
function myfunction(mydata)
{
alert(mydata)
}
</script>
<?php
$data =nl2br("hello \n world");
echo 'Click';
?>
Help Me, Thank's
Fixed
<script>
function myfunction(mydata)
{
alert(mydata)
}
</script>
<?php
$data = str_replace("\n", '\n', "hello \n world");
$data = preg_replace( "/\r|\n/", "", $data);
echo 'Click';
?>
Add an additional treatment to your string to remove line breaks :
$data = nl2br("hello \n world");
$data = preg_replace( "/\r|\n/", "", $data );
Then echo
echo '';
instead of
echo '';
Add and escape simple quotes between the variable for javascript ton consider it a string
concat your var to the outputed string because between simple quotes, it will not be interpreted (on the contrary of double quotes).
Then if you just want to add a line break directly in the alert, you should just do the following :
$data = "hello \\nworld";
echo 'Click';
If you want to display HTML into an alert box, consider using a popin javascript plugin.
As mentioned in the comments, single quotes will not interpret variables. You need to switch your quote types around, and add quotes around the data variable:
echo "";
Related
My 1 file is city.html which contains the following code
<script language="javascript">alert("Page Called"); </script>
'Bhubaneshwar', 'Orissa', 'India'
My another file index.php contains the following code
$x=file_get_contents("city.html");
$x=array($x);
echo $x[0];
It shows the following output
'Bhubaneshwar', 'Orissa', 'India'
But I want single word output like this.
When I print $x[0], it should be Bhubaneshwar
When I print $x[1], it should be Orissa
When I print $x[2], it should be India
First you need to remove script tags
$x = file_get_contents("city.html");
$x = preg_replace('%<script[^>]*>.*?</script>%/m', '', $x);
and then you can use explode:
$array = explode(',', $x);
then you can trim and remove quotes:
$array = array_map(function($item) {
return preg_replace("/^'|'$/", trim($item));
}, $array);
Use explode to convert string to array:-
// Remove script tag
$string = preg_replace('#<script(.*?)>(.*?)</script>#is', '', $x);
// $string = str_replace(' ', '', $string); // Remove space from string
$string = preg_replace('/\s+/', '', $string); // Remove whitespace from string
// explode string
$x = explode(',',$string);
Hope it will help you :)
Try,
$x=file_get_contents("city.html");
$x=array($x);
$html = preg_replace('#<script[^>]*?.*?</script>#', '', $x);
$str = str_replace(', ', ',', $html);
$x = explode(',',trim($str[0]));
$remove[] = "'";
$result = str_replace( $remove, "", $x );
foreach($result as $cities)
{
echo $cities . "<br>";
}
Here is code that first removes the preceding script tag(s) and breaks down the remainder into an array:
$x=array_pop(explode('</script>', $x));
$x=preg_split("/'\s*,\s*'/", trim(trim($x), "'"));
The first of those two statements is only needed if you keep that script tag inside your HTML, which seems to be there for testing only.
To display the result, you could do this:
foreach($x as $item) {
echo $item . "<br>";
}
Output:
Bhubaneshwar
Orissa
India
Considerations
It is unusual to have such data format inside HTML files. HTML is intended for rendering data in a user-friendly manner, and that representation does not really fit.
If you are the creator of the HTML file, then consider moving to a JSON format. In that case your file would be named city.json and would have this content (the double quotes and brackets are required):
["Bhubaneshwar", "Orissa", "India"]
And the code would make use of JSON functions like this:
$json=file_get_contents("city.json");
$x=json_decode($json);
This way you really use standards, and the code is compact.
You could again display the contents of $x like before:
foreach($x as $item) {
echo $item . "<br>";
}
Output:
Bhubaneshwar
Orissa
India
If you are the creator of that file, and use PHP to create it, then make use of JSON functions as well, as follows:
$x = array("Bhubaneshwar", "Orissa", "India");
file_put_contents ("city.json", json_encode($x));
I've this PHP page:
<?php
$lines = array();
$lines[] = "I am happy";
$lines[] = "I'm happy";
foreach ($lines as $line){
$message = htmlspecialchars($line);
?>
<div onclick="alert('<?=$message?>');"><div>
<?php
}
It generates this HTML results:
<div onclick="alert('I am happy');"><div>
<div onclick="alert('I'm happy');"><div>
This code seems to be correct, however, clicking on second "div" element an error occurs.
The ' char is equivalent to ' and javascript generates an error:
alert('I'm happy');"
I solved this problem adding to code addslashes() PHP function:
$lines = array();
$lines[] = "I am happy";
$lines[] = "I'm happy";
foreach ($lines as $line){
$message = htmlspecialchars(addslashes($line));
?>
<div onclick="alert('<?=$message?>');"><div>
<?php
}
Correct results:
<div onclick="alert('I am happy');"><div>
<div onclick="alert('I\'m happy');"><div>
My question:
Is this the right/best solution?
Which is the best practice to manage this kind of problems?
Don't try to generate JavaScript string literals by mashing strings together. json_encode will do it for you along with all the escaping (', ", new lines, etc) that you need for JS. It is preferred to addslashes because it is designed for the target data format and isn't generic (generic escaping solutions tend to miss things).
Encode data for HTML attribute values as the last thing you do to the data before putting it in the value. Don't encode for HTML before putting data into JavaScript.
foreach ($lines as $line){
$message = json_encode($line);
$javascript = "alert($message)";
$html = htmlspecialchars($javascript);
?>
<div onclick="<?= $html ?>"><div>
<?php
}
That said, a modern approach would generally keep the JavaScript separate and store the data in a data attribute.
You should also avoid putting click events on div elements, they aren't designed to be user controls so they can't (without more mucking about) be triggered by (for example) focusing the element and pressing enter which creates accessibility problems.
foreach ($lines as $line){
$html = htmlspecialchars($line);
?>
<button type="button" data-message="<?= $html ?>">...</button>
<?php
}
with
<script>
function buttonAlert(event) {
var message = event.target.dataset.message;
if (message) {
alert(message);
}
}
addEventListener("click", buttonAlert);
</script>
Your correct result is actually wrong, and would output I'm happy instead of I'm happy.
Asside from that, yes your solution will work and i don't see any problem with that way of doing in your particular context.
You can use below code
<?php
$lines = array();
$lines[] = "I am happy";
$lines[] = "I'm happy";
foreach ($lines as $line){ ?>
<div onclick="alert('<?=addslashes($line); ?>');"><div>
<?php } ?>
i have the following code, but it will not work. i am trying to create a script output:
echo "<script type=\"text/javascript\"><!--\n";
echo "SLIDES = new slideshow(\"SLIDES\")\n";
// Now loop through the files, echoing out a new select option for each one
foreach( $files as $fname ) {
echo 's = new slide()\n';
echo 's.src = \"http://cashbackflorida.com/wpradmin/modules/wprrets/photos/'.$result ->MLS.'/'{$fname}\n\"';
echo 's.width = \"560\"\n';
echo 's.height = \"420\"\n';
echo 's.alt = \"{$fname}\"\n';
echo 's.text = unescape(\"\")\n';
echo 's.link = \"\"\n';
echo 's.target = \"\"\n';
echo 's.attr = \"\"\n';
echo 's.filter = \"\"\n';
echo 'SLIDES.add_slide(s)\n';
}
echo '--></script>\n';
Don't do it this way. Just output the array to JavaScript and deal with it there.
var files = <?php echo json_encode($files); ?>;
You'll find the problem in your string escaping
echo 's.height = \"420\"\n';
You can't escape in single quote strings like that. So try this
echo "s.height = \"420\"\n";
You do NOT need to escape single quotes within double quotes or visa versa, but you can only get a newline character like that in a double quote string.
I would recommend HEREDOC for this kind of string writing though.
$fnamej = json_encode($fname);
echo << EOT
s.height = "420";
s.alt = $fnamej;
EOT;
I am also inclined to say that you'd be better off handling this in javascript. This may end up behaving very badly all of a sudden, and it will take up more bandwidth.
I am getting error in Firefox SyntaxError: unterminated string literal when i try to include following code:
<script>
function makeProdiv(data){
var tbl_body = "";
var tbl_row = "";
tbl_row +="<?php foreach($data as $row) {} ?>" (Error at this line)
tbl_body += tbl_row;
return tbl_body;
}
</script>
If i remove this row then error disappears.
What i am trying: I am trying to loop through the result returned from DB and display values.
Please anyone can assist?
You most likely have double quotes in the content generated by PHP. You need to escape them properly, or, providing you don't have single quotes in the PHP content, you could do:
tbl_row +='<?php foreach($data as $row) { /* ... */} ?>';
As noted in the comments, having newlines in your PHP content might also cause this issue. Remove or replace them.
Try something like this:
<?php foreach ($data as $row) { ?>
tbl_row += <?php echo json_encode(whatever); ?>;
<?php } ?>
Using json_encode() will ensure that the PHP value is correctly encoded for Javascript.
Try this:
<?php foreach($data as $row) {?>
tbl_row +=<?php echo $row;?>
<? }?>
what it contain?the
'data' that is passed to this function "makeProdiv(data)"
& $data.
I guess $data is an array of "tr" fetched from db.
I have a php function which generates a javascript alert popup.
This function accepts a parameter message.
My problem is that if message is a multiple line string, javascript won't alert the text because of the lack of '+' every line. How can I solve that?
function alert($msg) {
echo '<script type="text/javascript">alert("'.$msg.'")</script>';
}
/* DOESN'T WORK */
$msg = 'testtesttesttesttesttesttesttesttesttesttesttesttesttesttesttest.
testtesttesttesttesttesttesttest.
testtesttesttesttesttesttesttesttesttest.';
alert($msg);
/* WORKS */
$msg = 'testtesttesttesttesttesttesttesttesttesttesttesttesttesttesttest. testtesttesttesttesttest. testtesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttestttesttesttesttesttesttest.';
alert($msg);
The problem is multiline strings in javascript need to be split with a \ at the end of each line.
function alert($msg) {
echo '<script type="text/javascript">alert("'.$msg.'")</script>';
}
$msg = 'testtesttesttesttesttesttesttesttesttesttesttesttesttesttesttest.\
testtesttesttesttesttesttesttest.\
testtesttesttesttesttesttesttesttesttest.';
alert($msg);
Please user json_encode function in pass function parameter
json_code function is change link break into \n
<?php
function alert($msg) {
echo '<script type="text/javascript">alert('.$msg.')</script>';
}
/* DOESN'T WORK */
$msg = 'testtesttesttesttesttesttesttesttesttesttesttesttesttesttesttest.
testtesttesttesttesttesttesttest.
testtesttesttesttesttesttesttesttesttest.';
alert(json_encode($msg));
?>
This chrome