Php echo javascript with variables - php

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).

Related

passing more than one argument in javascript function

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

Fill jQuery or ajax by PHP var

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

write php inside javascript alert

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>;'; ?>

using php include in jquery

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.

PHP-generated javascript and quote marks

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.

Categories