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>
...
Related
I have a pre-written code in Php where JavaScript function is called
echo "<a href='javascript:submittemplate(".$temprow['templateid'].");'>".$temprow["templatename"]."</a></td>";
and the script is :
<script>
function submittemplate(templateid)
{
window.document.location.href = 'index.php?module=Users&action=UsersAjax&file=TemplateMerge&templateid='+templateid;
}
</script>
Now I wanted to pass one more argument In this function.
What I did was this :
echo "<a href='javascript:submittemplate(".$temprow['templateid'].",".$mode.");'>".$temprow["templatename"]."</a></td>";
<script>
function submittemplate(templateid,mode)
{
alert("anything");
window.document.location.href = 'index.php?module=Users&action=UsersAjax&file=TemplateMerge&templateid='+templateid;
}
</script>
The Later code does not work.
What am I doing wrong ?
if the mode variable is a string this will raise an error.
e.g. alert(myString Is Here) // throw error
it should be alert("myString Is Here");
so you must add quotation to be like this :
echo "<a href='javascript:submittemplate(".$temprow['templateid'].",\"".$mode."\");'>"
note the \"
I'll guess that you are producing invalid Javascript syntax because of the values your are outputting. Open your browser's Javascript Console to debug your Javascript and see any errors.
When outputting PHP values to Javascript, you should make sure they won't break the syntax. The best way to do that is to JSON-encode them, since JSON is valid literal Javascript. Just as you should also HTML-encode your values in HTML:
<?php echo htmlspecialchars($temprow["templatename"]); ?></td>
Since this is a terribly unreadable one-liner, you should look into binding the onclick event to the link using Javascript, not use a href="javascript:" target. See http://en.wikipedia.org/wiki/Unobtrusive_Javascript#Separation_of_behavior_from_markup.
Do not use the javascript: protocol, use onclick and return false
Why use JavaScript at all???
<a href="'index.php?module=Users&action=UsersAjax&file=TemplateMerge&templateid=<?PHP echo $temprow['templateid']; ?>">.....
you need to use escaped double quotes around arguments
...submittemplate(\"".$temprow['templateid']."\");'>".
since you're passing strings
Basically, the code below will generate divs which are then captured using the jquery .ajax function as the data object and appended to the div with ID='textResp':
while($row = mysql_fetch_array($result_new))
{
/* Echo the result as Jquery */
echo "
<script>
jQuery(document).ready(function(){
$('#textResp').append(<div>".$row['Title']."</div>');
});
</script>";
}
This code works fine, but when I add a class to the div:
$('#textResp').append(<div class='class'>".$row['Title']."</div>');
The whole world blows up and it sends the ajax calls into an infinite loop.
Has anyone ever heard of this... or am I just writing my javascript wrong?
I know that I shouldn't be echoing javascript, but I really didn't want to have to explode the result of the string captured in the 'data' object to add the '<div class='class'>explode_result_1</div>'
I don't see how this would cause an infinite loop, but you have quote issues. First, you're missing one before the <div. But more importantly, you'll need to escape some of those quotes. You have double quotes used for your php strings and then single quotes within that used for your javascript. The problem comes in when you put a class and try and use single quotes for that too, it ends the javascript string and just makes a mess. Try this:
"$('#textResp').append('<div class=\'class\'>".$row['Title']."</div>');"
$('#textResp').append('<div class="class">'.$row['Title']."</div>");
You have to use double quotes in HTML (I think that's a must), but you are also missing an opening single quote in your append parameter. Change to this:
$('#textResp').append('<div class=\"class\">'".$row['Title']."</div>");
What im trying to do, is use php include within a jquery append attribute. something like this:
$('a.popup[href^=#]').click(function() {
$('body').append('<div id="content" class="popup_block"><?php include( SITE_URL . 'activity/popup.php' ) ?></div>');
My script is in a php file, server side, so that i could accomplish this, but im not sure how to go about it. When it comes to html, css etc. I can combine it and php within the php file, but when it comes to javascript, its the quotes that confuses me, and when and how to use the brackets. This might sound confusing lol. Anyways, does CDATA have anything to do with it? I've never used it before, but I should atleast learn it's use.
The PHP interpreter will only look for <?php and ?> tags and try to evaluate anything in between. It doesn't care about surrounding quotes. You need to make sure though that the result of whatever PHP does is valid Javascript.
var foo = '<?php include 'foo.php'; ?>';
becomes
var foo = 'This is the content of foo.php.';
after PHP is done with it.
If there are any quotes in foo.php, it may become this:
var foo = 'This is the 'content' of foo.php.';
which is invalid Javascript syntax. You'll need to escape any character of foo.php that may cause such invalid syntax, for example with addslashes. This can be quite cumbersome though, so I'd advise to look for an alternative this to begin with.
You can encode the value using JSON, which is definitely syntax safe:
var foo = <?php echo json_encode("Some string with 'quotes'."); ?>;
Generating code in code is always tricky, try to not do it and stick to language neutral data interchange formats like JSON or XML.
If you are 100% sure you don't have any single quotes in your include, there should be no problems with how you have it.
If you want to visualize it, copy all of your generated code from the included php file and paste it right into the main page inside of the append(). See how it looks. This will give you a good idea of what the browser will end up with.
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.
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.