Calling a javascript function on a php variable - php

Javascript:
function capitalizeFL(string) {
return string.charAt(0).toUpperCase() + string.slice(1);
}
PHP:
echo "You have chosen a <script>document.write(capitalizeFL(".$race."));</script>";
$race contains a string. What I would like is simply to capitalize the first letter of the php variable $race, using the Javascript function above, and print it on the page.
I could find another way of doing this, but this JS-PHP mixing thing is confusing to me and I'd very much like to figure out WHY this doesn't work.

Look at the generated JavaScript.
document.write(capitalizeFL(value_of_race));
That's an identifier, not a string literal. You need to include quote marks in your generated JS.
Given a string, the json_encode function will output the equivalent JS literal (even if it isn't valid JSON). Use that to convert your PHP variables into JS literals.
$js_race = json_encode($race);
echo "You have chosen a <script>document.write(capitalizeFL($js_race));</script>";

echo "You have chosen a <script>document.write(capitalizeFL('".$race."'));</script>";
You can try above code.
Javascript string must be wrapped by ''.

Related

Is it possible to print php variable withing a variable?

I have a very simple question. But is really making me crazy.
I have a statement say:
example and example with one php variable like $loggedin_user_name
First of all, I want to store the above sentence in MySQL database and then take it back whenever I want to print the above statement. It seems that their is no issue.
But when I tried to print data after extracting from database it is printing the same statement. But i guess, it has to print the logged in user name instead of $loggedin_user_name in the above statement.
So, is it possible to print the variable within the variable? If yes, please suggest a way.
use sprintf()
$str = "example and example with one php variable like %s";
Then load it from database and fill
$out = sprintf($str, $loggedin_user_name);
If it is always the same variable name, I would suggest using
echo str_replace($fromDb, '$variableToReplace', $variableToReplace);
You can use preg_match to find you variable name in string and then replace it with str_replace.
$name = "ABC";
$bla = "$name";
echo $bla; //ABC
Will always be "ABC", because PHP is evaluating your variable when asigning to $bla.
You can use single-quotes to avoid that behaviour (like $bla='$name'; //$name) or you quote the $-sign (like $bla="\$name"; //$name). Then you can store your string like you wanted into your database.
But you can not (only when using eval(), wich you MUST NOT DO in good PHP-Code) build this behaviour, that php has, when printing fulltext.
Like Mentioned in another answer, you should use printf or sprintf and replace the $loggedin_user_name with %s (for "string).
Best would be to concatinate a string:
$exampleWithUsername = 'example' . $loggedin_user_name;
echo $exampleWithUsername;
'example' is a hardcoded string, but you can give it a variable containing string $example, or directly concatinate $username into $example.
You can use eval function, it can be used like your example:
$loggedin_user_name = 'bilal';
$str = "example and example with one php variable like $loggedin_user_name";
eval("\$str = \"$str\";");
echo $str;
Cons:
If your str variable or string/code which you give to eval as a parameter is filled by users, this usage creates a vulnerability.
In case of a fatal error in the evaluated code, the whole script exits.

Calling a javascript function while passing PHP variables

I am trying use a javascript function while passing php variables in it. For example:
onclick="alert(<?echo $row['username']?>)";
Now this does not work, instead gives an error-ReferenceError: Can't find variable:right_username(here the right_username is the answer i expect in the alert).
However if instead of username i use EmpID:
onclick="alert(<?echo $row['EmpID']?>)";
EmpID being an int in the database works just fine.
Because $row['username'] is a string, you need quote it, or the javascript will think it as a variable.
$row['EmpID'] is a number, so it shows.
onclick="alert('<?echo $row['username']?>')";
You forgot your quotes:
onclick="alert('<?echo $row['username']?>')"

passing a parameter from javascript to php

Hello everybody I'm trying to pass a parameter to my controller.php from javascript, but it doesn't pass and gives me error of undefined URL. kindly help me i shall be thankful to you...Here is my code
function JSfunction(assetid)
{
window.location="controller.php?command=delete&assetid=".assetid;
}
You're mixing PHP and JS, you use + to concatenate strings in JavaScript
Change the code to this and it should work:
function JSfunction(assetid) {
window.location="controller.php?command=delete&assetid=" + assetid;
}
What you are doing now is creating a string and accessing the assetid attribute of that string which is undefined.
you should set window.location to the full URL, not just the relative URL. I.E.
window.location="http://foo.com/controller.php?command=delete&assetid=" + assetid;
BTW, JS uses + to concat, not .
You must include server address, if it is being used locally,it can be denoted by http://localhost/AppName/pages?QueryString.
Concate string with plus sign, dot is used in php script for concatenation.

passing a string variable from php to a JS function

I was looking for a way to pass a string(variable saved in a form of $x) from php to Java Script and I found so many codes to solve that, but my question is : does those strings have to be declared global?!
i did declare it as a global variable but still no response ..!
any other suggestions?!
Pass a PHP string to a JavaScript variable (and escape newlines)
I tried most of these codes, none of them worked,
As the others have said, all we can say is that you are doing something wrong. You can place PHP variable values, strings or otherwise, wherever you want in your JavaScript code, since PHP is server-side and can do whatever you like on the client side.
This will help you to solved the issue of passing string variable value by calling the javascript function within php scrpt. :)
<?php
$testStrFileName = "test.jpg";
$file_name = "<script>". $testStrFileName ."</script>";
//<sample tags/>
echo 'Delete';
?>

do things with the return value of smarty function?

We have this Smarty function that returns HTML code for templates. However it is also possible that the function returns a null string, which we now wish to identify. Our system has been running stably for years, so I am looking for the least invasive possible solution.
Is it possible to assign the return value to a smarty variable? I have tried assigning it to a Javascript variable, however, because part of the HTML is user generated, the return string could be a mixture of double and single quotes, which causes problems in IE (unfortunately the majority of our user base).
<script type="text/javascript">
var html = '{smarty function}'; //IE chokes on mixed quotes
</script>
Any help appreciated!
Use escape modifier, for example:
{$variable|escape:'quotes'}
For smarty function, you can first try if {smarty_function|escape:'quotes'} works, if it doesn't then you have to assign the output of the function into a variable first before escaping it, and for that you use capture:
{capture name=mycapture}{smarty_function}{/capture}
{$smarty.capture.mycapture|escape:'quotes'}

Categories