I'm generating some javascript in my PHP code, and I need to assign some php variables to javascript variables. Unfortunately, sometimes my PHP variables contain quote marks. for instance:
$foo = "'Dis here be a \"string\"";
print "<script type='text/javascript'>var foo = '{$foo}';</script>";
will generate a javascript error because the resulting javascript will look like this:
<script type='text/javascript'>var foo = '"'Dis here be a \"string\"';
I know I can use regexp on $foo to replace all ' marks with \' but this is hard for various reasons. Is there anything I can do short of that? Something akin to the perl q() function...
Tried doing this?
$foo = "'Dis here be a \"string\"";
echo '<script type="text/javascript">var foo = "'.addslashes($foo).'";</script>';
See: http://php.net/manual/en/function.addslashes.php
I use json_encode().
http://ie2.php.net/manual/en/function.json-encode.php
This should be a step in the right direction:
addcslashes($str, "\"\r\n\\\t/\0..\37");
Are you sure? Isn't it:
var foo = ''Dis here be a "string"'
In order to prevent the double ' try:
$foo = "\'Dis here be a \"string\"";
or
$foo = '\\\'Dis here be a "string"';
It's also worth noting that you can use a PHP file as a JavaScript file
<script type="text/javascript" src="js/main.php"></script>
And you're able to execute PHP code in that file, as well as output JavaScript code by echoing from PHP.
Since you are using the final value in JavaScript, I would use json_encode:
$foo = "'Dis here be a \"string\"";
print "<script type='text/javascript'>var foo = " . json_encode($foo) . ";</script>";
And it will correctly output:
<script type='text/javascript'>var foo = "'Dis here be a \"string\"";</script>
Notice I didn't put an extra set of quotes around the json_encode function. It will add the necessary quotes to make it a valid JavaScript string automatically.
Frank Farmer's answer is interesting, but it's escaping some things that don't need to be escaped, like tabs.
Try this snippet, it works just fine:
<script type="text/javascript">
alert("Hi!\n\tHi!\n<?php echo '\tHI!',"\\n\tHI!";?>");
</script>
Since I'm always connected to a database in my PHP scripts that pass text directly into Javascript strings, I lean on real_escape_string to do my dirty work. addslashes() doesn't handle newlines and those sometimes sneak into strings I'm passing on to Javascript.
A simple $sql->real_escape_string($string) makes it all better, escaping whatever the database spits out into a Javascript-friendly form.
Related
I've been trying to get this to work for a while now, and have yet to find a solution online that works. I'm still fairly new to PHP so forgive me if the question is dumb.
I'm using a PHP document to read data from a text file. That PHP document is called as a script to the HTML document which actually displays all the information on the webpage.
So to my understanding, I have to use echo "document.write("")"; to output stuff, which works fine.
However, when I try using variables, it doesn't seem to work. For example I'm trying to do:
<?php
$test = "Hello";
echo "document.write("$test")" ?>
Am I missing something?
The specific reason your code is not working is your use of quotes. You can't enclose double-quotes within double quotes unless you escape them first - like this:
echo "document.write(\"$test\")" ?>
However, there is a deeper problem here. You don't need the Javascript at all. You could just do:
echo $test;
Lastly, document.write() has all sorts of unwanted side effects. If really do need that then you probably want to manipulate the DOM in Javascript directly, but that's a different question.
Just use echo to do what you want:
<?php
$test = "Hello";
echo $test;
?>
Value of $test will be outputted to the html.
document.write only works in JavaScript, try just use echo
If you want document.write to add the value of the $test variable in JavaScript, you are almost on the right track, but need to escape your quotation marks:
echo "document.write(\"$test\")";
because document.write(); is for javascript,to use variable just use variable name only in echo
I don't what you are trying to do, if you want to just output a text into a php usse echo
Your wrote it's incorrect
<?php
$test = "Hello";
echo "document.write("$test")";
?>
Correct way
<?php
$test = "Hello";
echo $test;
?>
I think you need quotes around the string in the document.write :
<script>
<?php
$test = "Hello";
echo "document.write('" .$test ."');";
?>
</script>
Which becomes :
<script>
document.write('Hello');
</script>
Which in turn displays this on the page :
Hello
If you want output into HTML then you can simply use echo function of PHP.
<?php
$test = "Hello";
echo "<script>document.write('" .$test ."')</script>";
?>
Unterminated string constant
hello
I have a php code which is:
$bodier .= "setInterval('updateClock(\"$date2\",\"clock$x\")',1000);";
I use it like this:
<body onLoad="<?php echo trim($bodier) ; ?>">
it produces:
<body onLoad="setInterval('updateClock("2012-10-31 13:14:01","clock0")',1000);
setInterval('updateClock("2012-08-30 13:10:31","clock1")',1000);
setInterval('updateClock("2012-08-30 10:16:46","clock2")',1000);
setInterval('updateClock("2012-08-30 10:17:28","clock3")',1000);
setInterval('updateClock("2012-09-07 10:17:47","clock4")',1000);
setInterval('updateClock("2012-08-30 10:18:27","clock5")',1000);
setInterval('updateClock("2012-08-29 10:18:41","clock6")',1000);">
and it products an error:
Unterminates string constant
What am I doing wrong
I have also tried copying psting simpley the output as hardcoded instead of the php echo part
valid html syntax is
<body onLoad="setInterval('updateClock(\"2012-10-31 13:14:01\",\"clock0\")',1000);">
you see, nothing breaks.
You are using " in two different meanings. You shouldn't use them within your onload string definition. Try instead to define a function with your setInterval lines and load the function name in the onload attribute.
(or escape the double quotes of course!)
You are doing common mistake here by putting unescapped quotation chars in the content string. See this example:
"foo"bar"com"
You may say that the string is foo"bar"com in fact it is foo as the next " closes the whole string. Same with your code. HTML parser sees: "setInterval('updateClock(" as your onLoad script. Which is wrong.
EDIT: Some characters needs special escaping for HTML and these are called entities. So whatever you output to be used with HTML, you may want to always pass it through htmlspecialchars() function, to stay on safe ground
You properly escaped the " in your php code, but you also need to make sure it is escaped in the HTML that gets parsed by the browser!
Use ".
This topic may be useful.
You're mixing up " and ' on various occasions in your code.
try something like this (also includes usage of functions, instead of strings in the setInterval() function and separating JavaScript from HTML markup):
<script>
function clockTimer( time, clock ) {
setInterval( function(){ updateClock( time, clock ) }, 1000 );
}
function onLoader() {
clockTimer("2012-10-31 13:14:01","clock0");
clockTimer("2012-08-30 13:10:31","clock1");
clockTimer("2012-08-30 10:16:46","clock2");
clockTimer("2012-08-30 10:17:28","clock3");
clockTimer("2012-09-07 10:17:47","clock4");
clockTimer("2012-08-30 10:18:27","clock5");
clockTimer("2012-08-29 10:18:41","clock6");
}
window.onload = onLoader;
<script>
<body>
...
Is it possible to fill jQuery variable by PHP???
I mean something like this:
<?php
$string_php = "50%";
?>
And with "$string" variable I want to fill jQuery:
var jquery_string = "$string_php";
$('.bar1').animate({'height':'jquery_string'},500);
The code above is only idea how I would like to be working
Yes but with php tags <?php ?> (so that php knows its code):
var jquery_string = "<?php echo $string_php;?>";
$('.bar1').animate({'height':jquery_string}, 500); // no quotes for variables
It is possible because PHP (server-side) runs before jQuery (client-side). The page first goes to server and server returns the response (php code is parsed there) to the browser.
Sure
var jquery_string = "<?php echo $string_php;?>";
Since PHP is processed first on the server and the result is then sent to the user's browser, this is easy, and often done.
The above code would result in:
var jquery_string = "50%";
You would, however want to modify your second line, removing the quotes from the variable so it was:
$('.bar1').animate({'height':jquery_string},500);
since keeping the quotes around jquery_string would make force it to be interpreted as a string whereas you want a variable.
The end result would be the equivalent of:
$('.bar1').animate({'height':'50%'},500);
For simple variables, just do as the users said.
F.ex. var jquery_string = "<?php echo $string_php;?>"; (taken from #Blaster's solution).
In other words:
The most simple solution is to output a php variable that we intend to use as string literal via echo anywhere we define the variable.
But: a correct approach would be that everytime we use a serverside variable as a Javascript string, it should be encoded, because the above solutions would fail when double quotes are present. Here json_encode may come handy.
var jquery_string = <?php echo json_encode($var); ?>;
Code example
We want Javascript alert the string "Hey", dude!
$string = "\"Hey\", dude!";
echo "alert(\"" . $string . "\");";
results in:
alert(""Hey", dude!"); <--- will give Javascript error
Instead:
echo "alert(" . json_encode($string) . ");";
results in:
alert("\"Hey\", dude!"); <---- correct JS code
have a question about a php echoing script that has a link to a javascript with some variables. I need to know the format for the echo so it will work properly. Could anyone shed any light on this? My code is posted below
echo "<a href='javascript: toggle('variable1', 'variable2')'><label1 for='nameEditor'>Manage</label1></a>";
Now when you hover over the link it just shows javascript:toggle( Now I have tried multiple things and I still cant get it to work. Anyone have any suggestions?
Assuming variable1 and variable2 are the PHP bits you want inserted into the javascript, then
echo "<a href='javascript: toggle('$variable1', '$variable2')'><label1 for='nameEditor'>Manage</label1></a>";
However, be aware that if either of those variables contain Javascript metacharacters, such as a single quote, you'll be breaking the script with a syntax error (think of it as the same situation as SQL injection).
To be sure that the variable's contents become legal Javascript, you'd want to do something like:
<script type="text/javascript">
var variable1 = <?php echo json_encode($variable1); ?>;
var variable2 = <?php echo json_encode($variable2); ?>
</script>
...
try like this:
echo "<label1 for='nameEditor'>Manage</label1>";
you have to escape \ quotes
It's because you're mixing your quotes that the browser see. Do this:
echo "<label1 for='nameEditor'>Manage</label1>";
If you escape the double quotes (\"), you'll be fine. The browser itself is seeing '''' (all single quotes), so you need to retain "''" (double,single,single,double) in your html element attribute, irregardless of PHP (except for the escaping).
I am trying to pass a php variable inside javascript bt it is not working.
Comment
Is it possible to do so or I may be incorrect somewhere...
Thanks for your response in advance! :)
First of all, you probably should change 'java' tag to 'javascript'.
Regarding your question - PHP is parsed on the server side, while Javascript runs on the client side. If you are not going to use AJAX and asynchronous calls, you could write values to the JS source, like this:
<script type="text/javascript">
var foo = <?php echo $yourData; ?>;
alert(foo);
</script>
Comment
You're dynamically generating Javascript. You will save yourself some headaches if when you need to do this you, keep it simple. Transfer the data from PHP to Javascript in the simplest way possible at the top of the page:
<script type="text/javascript" >
var $current = '<%? echo $current; %>';
</script>
As others have pointed out, you will want to encode and quote your php variable, using json_encode (in which case you probably won't need the quotes), or a simpler escape function if you know the possible values.
Now, your inline code can be simpler:
Comment
A final recommendation would be to pull this out into its own function, and use the "onclick" attribute.
Use json_encode() if your PHP has it.
This will automatically quote and escape your string and ensures that special characters are properly encoded to prevent cross-site scripting (XSS) attacks.
However, I think you will have to pass UTF-8 strings to this function.
And vol7ron has a good point – you should put a semicolon ; after your statement and put a space between that and the question mark ? for better legibility.
Comment
You can also pass booleans, ints and even entire arrays to json_encode() to pass them to JavaScript.