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
Related
I'll show the main parts of the code as most of it is irrelevant:
$url = $row['url'];
echo "<div id='anything'><img id='$url' src='$cover' alt='$title' onclick='myFunction($url)'>";
and the javascript function:
function myFunction(something) {
alert (something);
}
I recieve the following error in firebug:
missing ) after argument list
[Break On This Error]
myFunction(http://anything.com/anything...
-------------------^
I am relatively new to javascript but I can tell it is obviously not allowing the ":" from the url. However, I can't change or alter the id, as I need to alert the exact id of the Image.
I have made this work in a different format without the php, so I assume it's there where the problem lies?
The URL needs to be a string, but you're just outputting the string's contents.
You could just put quotes around it as suggested elsewhere, but that's at best an incomplete solution.
Fortunately, PHP gives you a better answer: json_encode combined (in your case) with htmlspecialchars. This is a function that (amongst other things) will properly wrap a string for you such that you can use it in JavaScript code. So:
$escapedUrl = htmlspecialchars(json_encode($url));
then
...onclick='myFunction($escapedUrl)'...
json_encode is for encoding text as JSON, but as JSON is a subset of JavaScript literal notation, and json_encode quite happily returns a valid, properly-escaped JavaScript string...
You need the htmlspecialchars as well because you're then outputting the JavaScript code you're generating into the onclick attribute, and the content of all HTML attributes in HTML text (even ones with code in them) must be properly encoded so (for instance) & must be &, etc.
Do this:
$escapedString = json_encode($url);
echo "<div id='anything'><img id='$url' src='$cover' alt='$title' onclick='myFunction($escapedString)'>";
T.J. Crowder is right, and you can check this out for more information:
What is the correct way to escape text in JSON responses?
Why is my first solution incorrect (even if it seems to work with 1 case)?
Read this: http://kunststube.net/escapism/
echo "<div id='anything'><img id='$url' src='$cover' alt='$title' onclick='myFunction(\"$url\")'>";
You basically need to print double quotes around the the value passed into the myFunction call:
onclick='myFunction(\"$url\")'
This is because you are doing something like this:
myFunction(http://anything.com)
Function parameter need to be enclosed within quotes or doble quotes in case of string parameters:
myFunction("http://anything.com")
So your echo should look like:
"<div id='anything'><img id='$url' src='$cover' alt='$title' onclick='myFunction(\"$url\")'>"
Also you should take into account that $url doesn't have to contain valid characters, so you should add some encoding/escaping (think in terms of XSS).
You have to use the encodeURI(uri) function:
"<div id='anything'><img id='$url' src='$cover' alt='$title' onclick='myFunction(encodeURI(\'$url\'))'>";
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
I write PHP inside JS in the following way
alert(<?php echo __("Error-login") ?>);
echo__("Error-login") correlates with an xml to translate in two languages with symfony, but now it does not work.
How do I fix this?
You are missing quotes in the alert() call.
alert('<?php echo __("Error-login") ?>');
Your line becomes
alert(Error-login);
As you can see, you are missing the quotes:
alert('Error-login');
If somebody uses quotes in the translation, this will also generate an error:
alert('Error's are here');
So you need to escape single quotes before you pass it to Javascript.
try this
<?php echo '<script language="javascript">confirm("Do you want this?")</script>;'; ?>
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).