Looking for a better way to show/hide an element - javascript

I'd like to know if someone could please show me a better way to show/hide an element on my page. This is how I am currently doing it.
At the very top of my index.php file, I have the code for my application. Here is the function which determines whether the form has been submitted and populates $_SESSION['prompt'] with data.
private function validateForm() {
if (isset($_POST['submit'])) {
$_SESSION['prompt'] = 'Form submitted';
}
}
And here is the element which I would like to show/hide depending on whether the form has been submitted located towards the bottom of my index.php file.
<p id="dialog">
<?php
if (!empty($_SESSION['prompt'])) {
echo $_SESSION['prompt'];
}
else {
echo '<script>document.getElementById("dialog").style.display="none";</script>';
}
?>
</p>

It's hardly a great leap in creative logic to work that one out
<?php
if (!empty($_SESSION['prompt'])) {
echo '<p id="dialog">'.$_SESSION['prompt'].'</p>';
}
else {
// nothing
}
?>
Why are you setting $_SESSION variables that you then use in the same file, as opposed to just variables? Are you using that data later?

Related

Is it possible to change HTML within PHP code?

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>

how to run a php code on clicking a hyperlink

I am working on a module, "who viewed your profile" in a social networking site project. When a logged in user clicks on hyperlink of a user, he must be directed to a dummy page called view.Information of user who has clicked link of other user and username of user whose link has been clicked is stored in a database table, views. I tried doing this by calling a function updatetable on click of the hyperlink and using this function, I want to send variables viewername and viewedname to view.php, which inserts a record into views table.
while($row=mysqli_fetch_array($res))
{
?>
<?php echo $row['username']; ?>
<?php
}
The above code displays links of all users and if a link is clicked, view.php page is opened where some php code has to be run.
My updatetable function is as follows:
<script type="text/javascript">
var viewedname,viewername;
function updatetable(viewedname,viewername)
{
$.post('view.php' { viewer_name:viewername, viewed_name:viewedname } );
alert(viewedname);
}
</script>
view.php code:
if ($_POST && isset($_POST['viewer_name']) && isset($_POST['viewed_name'])) {
$viewer_name = ($_POST['viewer_name']);
$viewed_name = mysql_real_escape_string($_POST['viewed_name']);
$con=new mysqli('localhost','root','','test');
if($con->connect_error) echo $con->connect_error;
$r=mysqli_query($con,"insert into views(viewer,viewed) values('$viewer_name','$viewed_name')");
}
Problems that I am facing:
alert is not being shown and insertion is not happening after view.php code.
Is there a mistake in the way I'm sending the viewer_name and viewed_name variables?
I am new to php. Please help me out! Thank you :)
Missing a (,) in your javascript post:
Replace with:
$.post('view.php', { viewer_name:viewername, viewed_name:viewedname });
PHP:
Its better doing it this way:
if ($_POST){
if(isset($_POST['viewer_name']) && isset($_POST['viewed_name'])) {
//Do your stuff
}
}

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]

Why yii captcha always shows a fixed picture?

Captcha works with no problem, but I have no idea why it's not generating a new code to dislay? I've looked into the documents but could find something that could solve my problem.
Is there something here that I'm missing. thanks.
public function actions()
{
return array(
'captcha'=>array(
'class'=>'CCaptchaAction',
'backColor'=>0xFFFFFF,
),
);
}
my view file:
<?php echo $form->labelEx($model,'verifyCode'); ?>
<?php $this->widget('CCaptcha'); ?>
<?php echo $form->textField($model,'verifyCode'); ?>
<?php echo $form->error($model,'verifyCode'); ?>
This is a known bug, that would most likely be fixed in Yii2.
On the Yii forums, user Black suggests:
My solution was to remove the session key on my controller action on get. Be careful not to remove it in any other place because it will probably fail on server validation.
$session = Yii::app()->session;
$prefixLen = strlen(CCaptchaAction::SESSION_VAR_PREFIX);
foreach($session->keys as $key)
{
if(strncmp(CCaptchaAction::SESSION_VAR_PREFIX, $key, $prefixLen) == 0)
$session->remove($key);
}
Another way to workaround would be to use JavaScript to click on the refresh link on every page load as mentioned by Soph:
$(function() {
$('#yw0_button').click();
});

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