Using JS function with parameters in php - php

The JS function is
function func(arg){
alert(arg);
}
When I do
echo "<div onclick=\"func($arg)\">Text</div>";
in php, it doesnt work
but when I do
echo "<div onclick=\"func()\">Text</div>";
it works and an alert with undefined text pops up.
How do I pass argument?

You need to quote the arguments. e.g.
<?php
$foo = 'bar';
?>
echo "function($foo) { ... }";
is going to produce the code
function(bar) { ... }
where bar will be interpreted as an undefined variable.
Safest method is to output your PHP variables via json_encode(), to guarantee you're producing syntactically valid javascript. e.g.
echo 'function(' . json_encode($foo) . ') { ... }';
which would produce (in this case)
function ('bar') { ... }

You need to wrap $arg in quotes. Example:
echo "<div onclick=\"func('$arg')\">Text</div>";
(using single quotes around arg as you're using double quotes for the string)

You can do like this (if $args exists of course)
echo '<div onclick="func('.$arg.')">Text</div>';

Related

Echo php string into onclick as arg

I have an html onclick that calls a javascript function below:
onclick="addInventory(<?php echo $product['id']?>)"
Once I add a second arg which is a string, the function breaks, I believe
I have put it in quotes but I'm not sure how.
Breaks using:
onclick="addInventory(<?php echo $product['id']?>,<?php echo $product['name']?>)"
PHP's json_encode, when used on a variable, will properly escape it for JS usage.
onclick="addInventory(<?php echo json_encode($product['id'])?>,<?php echo json_encode($product['name'])?>)"
For example:
>>> json_encode('This is "my string" and it has some \'nasty\' characters in it!');
=> "This is \"my string\" and it has some 'nasty' characters in it!"

How to add a variable with a URL inside of an if statement

Here is the code I wrote. The else is working. The if URL's are not.
<?php
if ( is_user_logged_in() ) {
echo'Set As Facebook Cover';
echo'Download';
} else {
echo'Set As Facebook Cover';
echo 'Download';
}
?>
To include a variable in a string, the string needs to be wrapped in double quotes, like
echo "This is a $var";
not echo 'This is a $var';
Or you can use the . to concat the strings:
echo 'This is a ' . $var;
Try this:
echo'Set As Facebook Cover';
echo'Download';
Final note, there is no need to use the ; after the variables because you are not ending the statement.
See a demo

Returning print_r as a string (PHP)

Am I doing this correctly? As I understand it, if I define the "return" value as true when I call print_r, it should return a string. I have the following function:
function alert($string) {
echo '<script>alert("' . $string . '");</script>';
}
And when I pass that function a regular old quote-encapsed string, it works just fine and dandy, but when I feed it this:
alert(print_r($array,true));
Nothing happens and I don't see an error, yet echoing print_r($array,true) works. Thanks for any help you can offer, I'm just trying to understand what's going wrong here even though it is obviously a very minor problem.
Use
<script>
alert(<?php echo json_encode(print_r($array, true)); ?>);
</script>
instead. Note the use of json_encode - this is to prevent any ' or other JS-metacharacters from introducing a JS syntax error, e.g.:
<?php
$name = "Miles O'Brien"; // note the '-quote in there
?>
<script>
alert('<?php echo $name ?>');
</script>
would give you:
alert('Miles O'Brien');
^-- start of string
^--end of string
^^^^-- unknown variable/function.
Your alert function has two problems handaling that input.
first, as metioned, your JS is missing qutes.
Second, the new lines should be converted to the string '\n'. otherwise your call to the alert function (in the js) will end in another line, which is not correct. for example:
alert("hello
world");
is invalid syntax.
so, this alert function will probably work:
function alert($string) {
$string=preg_replace('/\n/m','\\n',$string);
echo '<script>alert("' . $string . '");</script>';
}
print_r (as well as var_dump) outputs its content to stdout. However, you can control this behaviour with PHP's buffers.
Have a look at What is output buffering?, then http://www.php.net/manual/en/ref.outcontrol.php.

How to escape Javascript code that is echoed in PHP

I have this code that is captured in the jquery Data object from a php page.
echo "
var $d = $('<div/>', {
id: 'hi' + $('#textResp').children().length,
class: 'eventdiv',
html: 'hello'
}).hide().fadeIn(3000);
$('#textResp').append($d)
";
Problem is, the 's are not escaped. I have tried using /' to escape, but it comes up with an error. I am sure I am doing this wrong, does anyone know where to put the /' instead of '?
You could use a php nowdoc instead of quotes at all which would simplify things:
echo <<<'DOC'
var $d = $('<div/>', {
id: 'hi' + $('#textResp').children().length,
class: 'eventdiv',
html: 'hello'
}).hide().fadeIn(3000);
$('#textResp').append($d)
DOC;
then use whatever you want inside (quote or dquote). This is, of course, unparsed so if $d was actually referring to a php var then you would have problems.
Your apostrophes actually look fine. But, within a double quoted string, PHP will evaluate any string beginning with a dollar sign as a variable and not produce the desired result. Try replace the jquery related instances of $ with \$. Like this:
echo "
var \$d = \$('<div/>', {
id: 'hi' + \$('#textResp').children().length,
class: 'eventdiv',
html: 'hello'
}).hide().fadeIn(3000);
\$('#textResp').append(\$d)
";
use json_encode function in php, it behaves like the escape_javascript function in rails.
just pass a string argument to the json_encode function, and it return the escaped string for you, see the sample code below:
<?php
$form_html = <<HTML
<form action='...' ...>
<input type='...' name='...' ...>
...
</html>
HTML;
?>
var form_html = <?php echo json_encode($form_html); ?>;
$('.remote#create_form').html(form_html).slideDown();
You will need to use \ before all 's.
However, this is puzzling, why do you feel you need escape characters? It appears you are simply echoing this output, if this is between <script /> tags, you should be fine.
PHP will attempt to expand variables, $name, that occur in strings wrapped in double quotes. Since $d looks like a variable to the PHP interpreter, it will try to replace it with the variable's value.
Assuming that you don't have $d defined anywhere, that will produce an empty space and, possibly, a notice (if you are using error level E_NOTICE).
To prevent that from happening, escape dollar signs with a backslash (replace $ with \$)
Use single quotes for your string construction. Only use double quotes when you specifically are including variables that you want evaluated. PHP is trying to evaluate all of those $ references you have in there. By using single quotes, you will avoid many escaping problems.
echo '
var $d = $("<div/>", {
id: "hi" + $("#textResp").children().length,
class: "eventdiv",
html: "hello"
}).hide().fadeIn(3000);
$("#textResp").append($d)
';

PHP variable inside a javascript function

I'm attempting to put a php variable inside a javascript function and having no luck, here's what I got
<a class="code" href="javascript:void(0);"
onclick="javascript:if(window.dd && dd.elements)
d.elements.name1.moveTo(<? echo "$xpos"; ?>, <? echo "$ypos"; ?>);
return false;">
name1.moveTo(name1.x-20, name1.y+7);</a>
`
the moveTo() function works perfectly when I send it a javascript variable or simple numbers.
the reason its in a php variable at all is because I need the xpos to be inside a session variable to be accessed in other places. Afterwards I assign it as follows
$_SESSION['productcheck']['x'] = $xpos;
I'm kinda new to this, if you haven't already noticed, Thank you ahead of time :)
try not putting double quotes.
echo $xpos;
This is just to clarify, but you seem to have a typo (d should be dd). Corrected:
<a class="code" href="javascript:void(0);"
onclick="return (function () {
if(window.dd && dd.elements)
dd.elements.name1.moveTo(<? echo $xpos; ?>, <? echo $ypos; ?>);
return false;
})()"
>
name1.moveTo(name1.x-20, name1.y+7);
</a>
Some issues:
You don't need PHP variable interrpolation, $xpos by itself is fine
onclick should have only one expression that returns false, so you'd ideally wrap it in a function elsewhere. Here I used an anonymous one
Also, onclick need not start with 'javascript:, since it already is implicitly so.
My guess would that xpos and ypos are not in scope at the time that part of the page is processed.
Scope refers to the enclosing braces. for example the following will not work
$xpos = 100;
function printx(){
echo $xpos; // enclosing quotes not required
}
// call the function
printx();
Nothing will be printed
to fix it use the following
$xpos = 100;
function printx(){
global $xpos;
echo $xpos; // enclosing quotes not required
}
// call the function
printx();
this would then print 100

Categories