write php inside javascript alert - php

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

Related

Using PHP variable inside HTML, in a PHP file

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

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

Error call php in javascript

When I write:
alert(<?php echo "33333";?>);
it works.
If I echo a number, it works too. But if I write
alert(<?php echo "346346gj";?>);
it doesn't work.
Can someone tell me why?
alert(<?php echo "33333";?>); will output alert(33333);. And it's a correct javascript syntax.
alert(<?php echo "346346gj";?>); will output alert(346346gj);. It's not a correct syntax.
When you want to alert a string in javascript you write alert("346346gj"); or alert('346346gj');
So you must replace alert(<?php echo "346346gj";?>); with one of the following:
alert('<?php echo "346346gj";?>');
alert("<?php echo "346346gj";?>");
alert('<?php echo '346346gj';?>');
alert("<?php echo '346346gj';?>");
alert(<?php echo "'346346gj'";?>');
alert(<?php echo '"346346gj"';?>');
And there are still different conbinations.
Make sure you enclose the generated JS in quotes:
alert('<?= $stringVariable ?>');
I'm not sure if I understood your problem, but
alert(""+number);
Maybe I misunderstood you. If you want to print php values in JavaScript, you should request them via ajax. "Hardcoding" them isn't the way to go.
Because in javascript, strings need to be in quotes.. so try
alert('<?php echo "33333j";?>');
To output any kind of PHP value (except resources) directly into JavaScript, use json_encode.
alert(<?php echo json_encode($myvar); ?>);
$myvar can be pretty much anything, and it will always work. I alwyas use json_encode to put a PHP variable into JS.

Php echo javascript with variables

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

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