CSP convert inline onclick event with passing a PHP variable - javascript

I generate a list of applications from MYSQL using php
and then when you click on the relevant line it will open the application in a window,
something like:
<?php
$Path = $ApplicationPath
print "<td class='centerTextIncPointer'><img src='../images/printicon.png'onclick='printTheWindow($Path)'/></td>\n";
?>
The above is blocked by CSP policy, how to I get the popup window with the application to work with CSP?
I tried to use the following example but could not figure out how to pass the path as my Javascript skills are not great and the list is generated dynamically.
<?php
$Path = $ApplicationPath
print "<td class='centerTextIncPointer'><img id='LineId' src='../images/printicon.png'/></td>\n";
?>
script.js:
document.getElementById("LineId").addEventListener("click", myFunction);
function myFunction(){
// open the app in the window
}
Assistance is greatly appreciated :)

You can try this code:
<img src='../images/printicon.png' data-path="<?php echo $path; ?>" onclick="return !window.open(this.getAttribute('data-path'), 'Google', 'width=500,height=500')"/>

Related

Call javascript function within a PHP form

The architecture I use to load contents onto a common area on the web page is as below
I have a java script function within the form as shown below called javaScriptFunc which never gets invoked.
Is it possible to invoke a java script function within a form?
Please do let me know if more clarity is needed. I'll try to clarify. I'm stuck with this for a while now. I'd appreciate any help please
I think you are missing some PHP tags if I understand what you are trying to do correctly. Try this:
<form method="post" action="" id='somdId'>
<?php
require_once 'some_php_file.php';
if (isLoggedIn()) {
// Some PHP code here
?>
<script>
javaScriptFunc(<?php echo formatJson(someArgs); ?>);
</script>
<?php
}
?>
Not very clear what you want. You need to echo the script like this
echo ("<script type='text/javascript'>javaScriptFunc(" . formatJson(someArgs) . ");</script>");
provided you have already defined the function javaScriptFunc somewhere else in script.
For some reason, I the JS function doesn't seem to fire from within a form. I've worked around by re-writing the load logic to load the whole PHP page instead of a form. just a different way of doing things.

Unearthing a js php load/execution issue

Running a base web framework from https://github.com/panique/huge/
The overarching problem I have is: html table needing live updates to account for database (mysql) changes.
Where I'm stuck: I have added to the index/index.php page, the following javascript code to the end of the file (note: header and footers loaded around this index/index.php page) in attempt to refresh the need for updating the table every few seconds in order reload the html table based off of the mysql database state. The index/tableChange module simply gathers the mysql data and returns the query.
<?php echo "
<script language='javascript' type='text/javascript'>
function loadlnk() {
document.getElementById('tableHolder').innerHTML =
\"<object type=\"text/html\" data=\"<?php echo config::get('URL'); ?>index/tableChange\"></object>\";
setTimeout(loadlnk, 3000);
}
loadlnk();
</script>";
?>
When I test the index/tableChange snippet out, I am able to load the php by itself in its own individual webpage (but for the purpose of this question, I'm needing to load that content of tableChange into the index/index page).
I also tried adding the $(document).ready(function() { around inside of the script, but this didn't seem to help accomplish anything visible to changing the table.
I looked at what I understood and could find, but I don't think it's a quote issue.
You might like to remove the inner PHP tags and the echo statement and try like this:
<?php
echo "
<script language='javascript' type='text/javascript'>
function loadlnk() {
document.getElementById('tableHolder').innerHTML =
\"<object type=\"text/html\" data=\"" . config::get('URL') ."index/tableChange\"></object>\";
setTimeout(loadlnk, 3000);
}
loadlnk();
</script>";
?>
I found that I was getting an error in the console, similar to the following:
Load denied by X-Frame-Options: https://localhost/test/target.php does
not permit framing.
The solution, at least a quick one in this instance was to add a header before sending the output from /test/target.php ~ name header('X-Frame-Options: sameorigin'); then it worked just fine.

WordPress is_user_logged_in failing with HTML Scripting

Could someone please review why this below added code won't execute correctly? I've escaped the PHP scripting to display the HTML content in WordPress, but I can't get this thing to work!
The results are that, whether the user is logged in or not, the HTML content displays for everything. Strangely, though, I can't get the else { ... } part to render in HTML. I'm not too good with PHP, so please mind if I done something incorrectly.
I've tried debugging via NetBeans, but the IDE failed to detect anything on a fail-safe conditioning.
<?php
if ( is_user_logged_in() ) {
?>
<h2>Welcome to the Portal!</h2>
<p>Here you can manage all information with an authorised account. You can click on the button below to create a new entry.</p>
<button type="button" href="#" onClick="document.location = 'http://www.example.com'">Add Entry</button>
<?php
} else {
echo "<h1>Unauthorised!</h1>";
echo "<javascript>document.location = \'http://example.com\'";
exit;
};
?>
Alright, so I got the coding going. It turned out that, by default, WordPress didn't allow PHP execution in my pages. I installed a plugin named "insert PHP", modified the code to mix html and php and it worked!
[insert_php]
if (is_user_logged_in()){
echo "<h2>Welcome to the Portal!</h2>";
echo "<p>Here you can manage all entries with an authorised account. You can click on the button below to create an entry.</p>";
echo '<button type="button" onClick="document.location = \'http://somesite.com\'">Add Listing</button>';
} else {
echo '<h2>Unauthorized 401</h2>';
echo '<script>document.location = \'http://domain.tld'</script>';
};
[/insert_php]

How would I call a java script function using php if statement with $_SESSION

Hi I am creating a website with a login section this is working I am using HTML and PHP. What I am trying to do is one of my pages has a html button I want this to be disabled for certain users. at the moment this is what I have got.
this is the part that I use for the login details.
<?php
session_start();
$_SESSION["username"];
$_SESSION["password"];
$_SESSION["access"];
?>
I have got if statments that I am currently using which are
if($_SESSION["access"] == "Administrator"){
echo $Admin;
}
what I am trying to do is call a javascript function within a PHP if statement what i have got so far is
<?php
if($_SESSION["access"] == "Consumer")
{
echo '<script type="text/javascript">
Disable();
</script>';
}
if($_SESSION["access"] == "Administrator")
{
echo '<script type="text/javascript">
Enable();
</script>';
}
?>
the javascript functions that i am trying to call are
<script type="text/javascript">
function Enable() {
SubmitButton.disabled = false;
}
function Disable() {
SubmitButton.disabled = true;
}
</script>
I have also tryed
if($_SESSION["access"] == "Consumer")
{
echo "<script> Disable(); </script>";
}
Im just wondering if I have typed something in wrong or if I have forgotten to put something in.
any help would be much appreciated.
Looking at your code you have couple of issues:
Mixing your PHP logic and pure HTML is (usually) not a good idea.
Instead I would suggest you move your access checking logic fully on the server side and display the button accordingly (disabled or enabled) based on the user's access.
Example:
<?php if($_SESSION['access']): // Only show the button for users with access ?>
<button type="submit" value="Submit" <?php echo ($_SESSION['access'] != 'Administrator' ? 'disabled' : ''); // Button disabled for everyone but administrators ?> />
<?php endif; ?>
And let me point out the obvious (as mentioned by the other answers), that's not 100% bulletproof. The user can still manually submit the button even if he is not an administrator by editing the page's HTML on the fly. That's just a UI fix. The real check should be done on the server side once the button is submitted (e.g. is the user logged in, does he have a cookie on his computer that identifies him as an administrator, does he have a session cookie set, etc).
Calling JS in random places, e.g. in the header can have unexpected consequences.
You better wait for the page to be loaded fully before calling any JS functions. You can do that via jQuery easily, but make sure you include the jQuery library before that in your header like so.
Afterwards you can call any JS after the page is loaded by placing them within the following block:
$(function(){
// Place your JS calls here, e.g. call to Enable()
});
String concatenation in PHP is done with a dot . and strings can be multiline
This code which you used is just plain wrong.
echo '<script type="text/javascript">'
, 'Enable();'
, '</script>';
You should use something like:
echo '<script type="text/javascript">'
.'Enable();'
. '</script>';
or better:
echo '<script type="text/javascript">
Enable();
</script>';
PHP doesn't use , sign for joining. Use ..
But otherwise it should work, except that you should define SubmitButton in advance of using it.
<?php
echo "<script type='text/javascript'>";
// if the id of your element is "submitButton"
echo "var submitButton = document.getElementById('submitButton');";
echo " function disable(){ submitButton.disabled=true; }";
echo "</script>";
?>
After that you can use it as you did..
<script type='text/javascript'>
disable();
</script>
Just be advised that denying access to some elements/functionality on your webpage with JavaScript alone is not a good practice - JavaScript is executed locally on the user's computer and therefore the user can modify it to gain an advantage.
Well, the problem may be that you're trying to call the javascript function before the HTML is ready (or finally rendered), so the browser, when executes the function doesn't find the button.
You could solve this placing your javascript code at the end of your page, or using jQuery and doing:
$(document).ready(function() {
<%php if ($_SESSION['access'] == 'xxxxx') {%>
Enable();
<%php } else { %>
Disable();
<%php } %>
});
Anyway, ALWAYS check user permissions on the server side, because someone could enable the button using Firebug or something else...

How can I use a theme option in a JS file?

I'm creating a Wordpress theme and have added an option which allowed users to change a font family using (simplified code): update_option('mytheme_font', $_POST['mytheme_font']);
How do I then get the value of that option in a JS file of the theme? I need it because I'm using Cufon to replace some H1's and H2's. Thanks!
You have four options I suppose.
Output your javascript to your page inside script tags. Easiest
<script>
<?php echo 'var x = 3;' ?>
</script>
Output the variable to your page and then read that from your javascript file. Clunky, but does mean you don't have to create some js globals.
<div id="x" style="display: none;">3</div>
var x = document.getElementById('x').innerHTML();
[Added] - Use AJAX to request the data and parse after page load.
Last and I don't recommend it, but setup php to parse .js files to dynamically produce javascript files. This way you could place a <?php ?> call in your .js files.
You could echo some thing like this in the <head> of the header.php
<?php
$defaultThemeFont = "myDefaultValue";
$userThemeFont = get_option("mytheme_font");
if($defaultThemeFont == NULL)
$userThemeFont = $defaultThemeFont
?>
<script>
<?php echo "var mytheme_font = $userThemeFont;"; ?>
</script>
Now you can access this variable from any JS file

Categories

Resources