Is it possible to change HTML within PHP code? - javascript

What is the easiest way to run Javascript code inside PHP, preferably without using external libraries? Specifically, I need the innerHTML of a div to change depending on some calculations performed using the user's form inputs that were captured earlier with $_POST in a separate form. How can I get the following JS code to run inside the following PHP code? (My most basic attempt was using echo command, but it's throwing up errors)
HTML:
<div id="output">
</div><!--#output -->
PHP (desired JS included):
if (count($valid_locations)<$num_of_locations){
echo '<script>const output = document.querySelector("#output");</script>;';
echo '<script>output.innerHTML = "<div class="alert-danger"> Trip unable to be created. Please adjust the budget/number of travelers/duration etc.</div>;";</script>';
}else{
createTrip($trips);
}
Right now, the IF condition is True and the code does run, but it echos ";" for some reason. I have verified that the condition is met and it runs by adding in a simple echo "this runs";, which did appear upon refresh. I just don't understand why it's outputting to the default echo space and the script isnt running to change the innerHTML of the output div. Is this even possible to do with PHP? If so, what's the best way? (doesn't need to be secure, won't be used publicly). I've heard of a few things such as ajax but it seems so complicated. Any explanations on stuff like that specific to this scenario would be greatly appreciated.

Following up on the comments, you don't need JS to achieve what you want. You could just use PHP
<?php
$output = null;
if (!empty($_POST)) {
//...
//... do stuff
//...
if (count($valid_locations)<$num_of_locations){
$output = 'Error occured - bla bla bla';
}
}
?>
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<?php if (isset($output)) {?>
<div id="output"><?= $output; ?></div>
<?php } ?>
</body>
</html>

Related

How could I refresh the following the php file? (Without the page reloading)

I've been playing around creating a control panel for gameservers, however I would love to show the user some CPU percentages. I totally can, but it doesn't update itself automatically. Here are my Codes
Note: This is not a working code, I mean it works, but only if you have load.php, which totally works, so I'm not going to bother showing it, it basically returns a number + %, to be able to modify the width of the progress bar.
What I want is pretty simple, I want the bar to update itself automatically. I just don't know why my code doesn't work.
<?php include '../includes/kezelohead.php'; ?>
<?php
include 'load.php';
//echo $cpu;
?>
<h5>Processzor Hasznalat</h5>
<div class="progress progress-striped" id="prog">
<div id='bar' class='progress-bar progress-bar-custom active' role='progressbar' aria-valuemin='0' aria-valuemax='100' style="width:100%;">
</div>
<script type="text/javascript">
var interval = setInterval(cpu, 2000);
function cpu() {
$("#scores").load("load.php #scores");
var data = <?php echo(json_encode($cpu)); ?>;
document.getElementById('bar').style.width = data;
//setTimeout(yourFunction, 5000);
}
</script>
<div id='scores'>
<?php
include 'load.php';
//echo $cpu;
?>
</div>
I've managed to solve the problem, with AJAX, so thanks everyone :)
I have used Ajax's load function, like so: $('#scores').load('load.php');

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.

Insert code with JS just like echo in php

I want to get some code snippets from a PHP server to be "injected" in HTML. Basically when I open page.php I get some text like "_off".
The injection works with this code, however I can't use php in this html since it is local.
<img src="images/test
<?php
{ echo "_off"; }
?>
.jpg">
JavaScript seems to be the logical step. But if I just enter this at the position where I want the text of course it doesn't work:
<script type="text/javascript"> $.get( "page.php", function( data ) { document.write(data); } ); </script>
Any ideas?
You need to use $('#someElement').html(data) or $('#someElement').text(data) if you want to write the data to a specific place on the page. You should avoid using document.write
Here is a fiddle to demonstrate: https://jsfiddle.net/yd9mx4d3/

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.

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

Categories

Resources