I have a web based tool. There is a login where username, loggedin and authorised are stored in session variables.
There is one particular page where I have a form that has multiple buttons, I wish to disable one button based on what the users authorisation level is. So if authorised is 0 (user) the button is disabled, else it's enabled as I've only got two authorisation levels, 0 & 1.
I've attached what I've done below, and to me it looks right, obviously it's not!
Here is the JQuery function:
$(function disable(){
$('#signBtn').attr('disabled', true);
});
Here is the PHP code:
if($_SESSION['authorised'] == '0')
{
echo "<SCRIPT LANGUAGE='javascript'>disable();</SCRIPT>";
}
Here is my HTML code:
<input type=\"submit\" name=\"save\" id = \"signBtn\" class = 'eBtnSubmit' value=\"Sign off by Chairperson\" />
If there is anyone out there that can see what my problem is I would really appreciate it...this is my last piece of the puzzle and I'm presenting this today (Software Intern).
So basically if the level is 0 call the function.
Regards,
Gary
No warranty because I don't have all the code
Change the static JavaScript Code to this
var disableSingoff = function () {
$('#signBtn').attr('disabled', true);
}
In your original code, you execute the disable() function right when the DOM is ready by wrapping it in $().
Change the PHP code to this
if($_SESSION['authorised'] == '0') {
echo "<script>$(function () { disableSignoff(); })</script>";
}
It might be easier to simply set the value in the HTML if possible
if($_SESSION['authorised'] == '0'){
echo '<button type="button" disabled="disabled">Click Me!</button>';
}else{
echo '<button type="button">Click Me!</button>';
}
This would work before the page even starts loading.
The other option would be to hook the window on load function.
window.onload = (function(){ [...] }
is the <input type=\"submit\" name=\"save\" id = \"signBtn\" class = 'eBtnSubmit' value=\"Sign off by Chairperson\" /> being echoed from a php statement? if not you can get rid of all the '\'s. they are not necessary when writing strictly html.
Related
I have researched many places to find an answer to this question, but they never quite answer my real question: What is the best/approved way to move to a new page within the same website? I have read that it is bad to use window.location because search engines will think you are hiding something. But, when I don't want to open a new window (window.open), then I don't know how else to do it. I use href anchors in links and form actions, where appropriate. But when I have menus or buttons with onclick, then I need something else.
Here's an snippet of my code:
my javascript: (with one option commented)
function gotoCat() {
var catcdF = document.catSelect.catcd.value;
<?php
echo "window.location.href='http://www.mysite.org".$pgmdir."services/busMenu.php?catF='+catcdF; ";
/*
echo "window.open('http://www.mysite.org".$pgmdir."services/busMenu.php?catF='+catcdF,'','resizable=1,scrollbars=1,toolbar=1,top=50,left=300,width=950,height=800,location=0'); ";
*/
?>
}
My dynamic SELECT list in a form (within PHP):
echo " <select name='catcd' id='catcd' size='8' onclick=gotoCat() > \n";
// display list of categories
if ($numcats == 0) { // print message text only
echo "<option value='0' >".$catMsg."</option> \n";
}
else {
for ($i=1; $i<=$numcats; $i++) {
$catcd_db = $catAry[$i][1];
$catName_db = $catAry[$i][2];
echo "<option value='".$catcd_db."'> ".$catName_db." </option> \n";
}
}
echo "</select>";
So, as you can see, I just want a method to allow the user a choice and then automatically go to the correct web page once selected. This is not always in a select list. Often it's when they want to exit or get an error:
if (mysqli_connect_errno()) {
echo "<br/> <p style='text-align:center;'> <button type='button'
class='buttonStyle' style='padding: 4px 20px;' value='Exit' ";
echo "onClick=\"window.location.href='http://www.mysite.org/services/catSelbus.php?rc=1&func=Rev'\" > ";
echo "Exit </button></p> ";
}
I cannot use "go back" because they need to go to a prior page, not the form they came from.
So, unless my navigation methods are really off-the-mark, I guess I need to know the acceptable method for using javascript onClick to move to the next page in the same website. Is window.location okay, or should I use something else?
Any opinions or suggestions are welcome!
To navigate to another page using Javascript, use:
window.location.href = "url";
That's how it's done and there's nothing wrong about it.
For the sake of argument, you could create a hidden link and simulate a click on it, but as I said, there's really no need.
You can use php header('location') instead:
<form action="submit.php">
<input type="hidden" value="test" name="hidden1" />
<input type="submit" Value="Exit" ... />
submit.php
<?php
if (isset($_POST['hidden1'])
{
header('Location: http://www.mysite.org/services/catSelbus.php?rc=1&func=Rev');
exit;
}
?>
More info about header('Location ...');:
http://php.net/manual/en/function.header.php
Instead of a hidden, you use your select's value and get it via the $_POST variable.
I want to enable or disable a div according to the session if it starts with an user or a guest. I want to do something like this:
First, i will evaluate if it is user or not by doing this:
<?php
if(!isset($_SESSION['idUser'])) // If it is Guest doesn't have id.
{
$guest=true;
} else {
$guest=false;
}
?>
then in jquery, i would like to say:
$('.box').click(function(){ // labBox appears when box is clicked
if(<?php $guest?>)
$("#LabBox").hide();
else
$("#LabBox").show();
});
Question: how can i use my php boolean var $guest to disable or hide some elements of my website?
Do i have to do two distinct php files? one for users and other for guest (e.g, home.php and home_guest.php)?
you could do the alternative such as
<script>
var guest = '<?php echo $guest; ?>';
$('.box').click(function(){ // labBox appears when box is clicked
if(guest === "true") {
$("#LabBox").hide();
} else {
$("#LabBox").show();
}
});
</script>
This would simply allow you to pass the PHP value to a Javascript variable, in order for you to use it within the onClick.
Remember: everything that reaches the client can be manipulated. Therefore, if you send an hidden element (say, an hidden <div>) any tech-savvy user can, and will, easily make them visible.
You MUST perform the checks about the login/guest status in your PHP script, and don't rely on jQuery to assemble the page at client side (hey, after all, the user may have disabled javascript altogether!)
You don't need two pages (eg: home.php and home_guest.php) to render different content based on the user level. Just use appropriately session/cookies and different echos.
Use a hidden input, populated by PHP, which jQuery can grab:
<?php
echo "<input type=hidden id=guestcheck value=$guest/>"
?>
if ("#guestcheck").val()) {
}
I personally like this method because it allows me to check the source when debugging to find out where any errors may be (for instance you can plainly see in the source when viewing the page whether or not GUEST is true)
It depends on contents of those files. If the only difference is visibility of the block, it's more reasonable to do the check inline.
<?php if (isset($_SESSION['idUser'])) { ?>
$('.box').click(function() { $("#LabBox").show(); }
<?php } ?>
Personally I would do it in the HTML rather than the JS file...
<?php
if(!isset($_SESSION['idUser'])) // If it is Guest doesn't have id.
{
$loggedin=true;
} else {
$loggedin=false;
}
?>
Then later on..
<?php if($loggedin===true){?>
<div>User is logged in</div>
<?php }else{?>
<div>Guest is viewing page</div>
<?php }?>
This means that the div for the user is not shown to the guest, whereas your currently solution only hides it from view (user could just use firebug/viewsource!
Why don't you just show/hide your div in the php depended on if they are a guest or not...
So...
<?php
if(!isset($_SESSION['idUser'])) // If it is Guest doesn't have id.
{
$guest=true;
} else {
$guest=false;
}
if($guest===true){
echo "<div></div>";
}
else{
//dont echo div
}
?>
PHP / server-side:
<?php
if(!isset($_SESSION['idUser'])) // If it is Guest doesn't have id.
{
$guest=true;
} else {
$guest=false;
// add #LabBox element from here to avoid junk/hidden elements for guests
}
?>
JQuery / client-side:
$('.box').click(function(){ // labBox appears when box is clicked
if (!<?php echo $guest?> && $('#LabBox').length > 0) {
$('#LabBox').show();
}
});
Then it is critical that any action requested by the user pass the "guest or not?" test before being granted from the server-side.
Here is my problem.. I have some JavaScript that I want to run, however I need it to be unique each time it gets inserted. I tried adding a variable to it that would change it, however it only changes it on the first call/display. Here is the script:
<script type=\"text/javascript\">
function validate_f( )
{
var x=document.forms[\"fill\"][\"textfield\"].value
if (x==null || x==\"\")
{
alert(\"Field cannot be empty\");
return false;
}
}
</script>
The actual form code is:
echo "<td width=\"10%\">
<form method=\"POST\"action=\"$actual_link\" id=\"fill\" onsubmit=\"return validate_f( );\">
<input type=\"hidden\" value=\"{$data['id']}\" name=\"id\">
<input type=\"text\" size=\"20\" class=\"BUTTON_INPUT\" name=\"url\" value=\"\" id=\"textfield\">
</td>
<td width=\"1%\">
<input type=\"Submit\" class=\"BUTTON_FILL\" name=\"fill\" value=\"\">
</form>
The problem is that form gets echoed multiple times with different links, but the script will only work the first time. So my only solution I could think of was to have the JavaScript echoed along with the form and have the function name changed on both the script & the form.
I hope what I'm trying to do makes sense, so basically I need "function validate_f( )" & "onsubmit=\"return validate_f( );\"" to change with each repeat/echo ..
if your text field is in every form you can use only one generic function like this that will work for all forms no matter their id
function validate_f() {
var x = this['textfield']
if (!x || !x.value) {
alert("field cannot be empty")
return false
}
return true;
}
I came up with a solution for this, and thought I would share it in case someone comes across this. But basically the form that is being echoed/repeated did get unique data on each time it repeated.. So basically I took that unique value and put it as the function & the form id.. It is pretty simple now that I look back at it, I just had to think really hard about how to get something unique that changed. Hope this helps someone..
I have a file called admin.php in which I have a button with the name send. What I want to do is when I click it, to make visible a link on the user's page, user.php. How can I do this?
I have a file with all my functions called functions.php in which I have a function called onSubmit($var); I initialize the variable $var is admin.php with the value $_POST['send'] but when I call the function in the file user.php I have no way of telling him who the variable $var is so I get 'undefined index'.
Is there another way to do this?
EDIT Added code
This is admin.php
<input type="button" name="send" value="Submit" /><br/>
require 'functions.php';
$posted = $_POST['send'];
onSubmit($posted);
This is user.php
require 'functions.php';
onSubmit($var); //here it says undefined index var because it doesn't know who the variable is
if($isSent == 1) {
<a style="visibility:visible;" href="test3.html" id="test3">Test3</a> <br/>
}
And this is functions.php
global $isSent;
function onSubmit($var) {
if(isset($var)) {
$isSent = 1;
}
}
Basically you need to use sessions like below:
if(isset($_SESSION['makeVisible']) && $_SESSION['makeVisible'] == true){
echo '<button>Button init</button>'; //you could also use html like the comment below.
}
/*
if(condition){?> <!-- this is now html --> <button>Button init</button><?}
*/
Then to set this variable on your admin page use:
if(isset($_POST['submitButton'])){
$_SESSION['makeVisible'] == true;
}
You'll also need a form for this method to work but there are other methods but I prefer this one.
<form name="buttonMakerThing" method="POST">
<input name="submitButton" value="Make button init Visible" type="submit"/>
</form>
Without an action the form defaults to 'POSTING' the form information to the current page. Making the condition if(isset($_POST)) return true.
You will need to add a $_SESSION declaration at the top of every php page you have on your site for this to work. It MUST go on the very first line of every page! for example:
01: | <?php session_start();
02: |//rest of script;
Please look more into $_SESSIONS for unnsetting/destroying your sessions and more uses for them :) http://php.net/manual/en/reserved.variables.session.php
Right I've done a bit of research on Caching and this is what I've come up with. It might not be 100% correct but it's a start as like I've said I've never tried it myself lol
In your admin.php I'd put this function in:
if(isset($_POST['send'])){
if($enabled == true){
$enabled == false;
}
else{
$enabled == true;
}
apc_add('enabled',$enabled);
}
Now to 'get' our $enabled var:
$enabled = apc_fetch('enabled');
Then to check the the var within your client page:
if($enabled == true){
echo ' button';
}
Now the only things I haven't fully looked at is the security of the apc_ function and the client usage. I believe it works for all clients of the server but I'm not 100% certain. Here the php manual to give better examples.
This is the method I was thinking of. But again I'm not sure on the security of it but I'm sure you can find something to keep it secure. The video is actually is tutorial for a Youtube API. But he does cover saving a variable to a cache text file which should be of use to you :)
If you have functions.php which defines functions, simply include it in admin.php file and then you can call the function from there and also pass value.
To put it simply I have this variable which carries a hyperlink:
$test3 = 'Move to Quotes';
and what I need is to execute this variable inside a switch case like below:
switch ($_POST['dropdown']) {
case "Select Folder":
echo "Please select";
break;
case "One":
exec($test3); <-- //here i want to run (if this is not execute, my misunderstanding) the link.
break;
case "Two":
header('Location: http://www.facebook.com/'); <-- //this is just a test
break;
default:
echo "<br></br>";
echo "Move multiple files:";
echo "<br></br>";
}
?>
<form method="post" name="theform" action="">
<select name="dropdown">
<option value="Move to Folder">Select</option>
<option value="One">One</option>
<option value="Two">Two</option>
</select>
<input type="submit" value="Move"/>
</form>
I'd like know how to execute the ahref link without the user clicking it, but simply set this link as a case and when the user submits the form, the selected case actions the hyperlink.
Any help appreciated.
MORE DETAIL
I understand that javascript and php are both seperate languages and that a better option would be to use Ajax, but my understanding of Ajax is limited.
To explain it better, this is what's going on in its entirety:
1) I have a mailbox with a selection of messages.
2) You are able to check these messages and then click a link "Trash Selected" which deletes the selected messages. This the link:
Trash Selected
The javascript function actions the php function in $muldel for all selected messages and updates the database.
This is the javascript function in question:
function inboxDelete(url) {
document.messages.action = url;
document.messages.submit();
}
archiveMove() is exactly the same, just duplicated temporarily to make things clear.
3) I have now re-used the ahref code to do the same procedure, but this time, for moving the selected messages into folders.
4) These folders can be selected from a drop down box - this is where the form comes in.
5) So although I can get it to work by adding a link like such:
$test3 = 'Move to Quotes';
echo $test3;
6) I now need this to work the same way but the link being changed, depending on which folder is selected.
That's the full extent to my problem, I hope this is more clear.
I am aware you can send variables into javscript using GET or POST and then carry out the function entirely through javascript. I have tried something like below, but to no avail:
<form method=post name="myform" action="<?php echo $PHP_SELF;?>">
<input type="hidden" name="formVar" value="">
<input type="text" value="Enter Text Here" name="myText">
<input type="text" value="Enter Text Here" name="myText2">
<input type="submit" value="Send form!" onClick="readmove()">
</form>
<?php
// Retrieve the hidden form variable (using PHP).
$myvar = $_POST['formVar'];
if ($myvar == "$mulmov"){
echo $mulmov;
}
?>
<script language="JavaScript">
<!--
function setText(){
document.myform.myText.value = document.myform.myText.value.toUpperCase();
}
function readmove(){
document.myform.myText.value = "<?php echo $myvar; ?>" ;
readmove2();
}
function readmove2(){
if (document.myform.myText.value == "$mulmov"){
document.myform.myText2.value = "<?php echo $mulmov; ?>" ;
<?php exec ('archiveMove(\''.$mulmov.'\'); return false;'); ?>
} else if (document.myform.myText.value == "$mulmov2"){
document.myform.myText2.value = "<?php echo $mulmov2; ?>" ;
}
}
</script>
First of all, you can't execute JavaScript from within PHP like this. At this point, the control has already moved to the server and JavaScript is run on the client-side.
Second of all Im assuming you dont want to just follow the link, you want to run the link's onClick event, since the href is just a hashtag. So you are trying to run a JavaScript function with PHP. You cant call a function in one language from a function in another language.
Its hard to tell what exactly you are trying to do, but if you want to run a function when a user selects a certain dropdown, write a php function that does what archiveMove() does. If you want this to happen without a page refresh, you can stop the submit process and call your archiveMove() function with javaScript and Ajax.
If elaborate on what exactly you are trying to do, maybe we can help more.
Ok, so the only difference between your working code and the not working code is that you want to dictate the submitted URL based on what is selected in the dropdown?
So you can use JavaScript to set the form action when the dropdown is selected.
BUT, It might be a better idea to submit the form with the same action everytime, and then use PHP to decide what to do. It seems like this is where you were headed initially. Just get the folder id in the switch statement and call a function to make your edits:
The PHP can be similar to the way you had it:
switch ($_POST['dropdown']) {
case "Two":
// set folder id
$folder_id = 2;
break;
}
moveMessages($_POST['Messages'], $folder_id);
function that moves the messages where they need to go.
function moveMessages($messages, $folder_id){
// depending on your form setup
foreach($data as $id => $value ){
if($value){
// code to move to folder
}
}
return true;
}
If there are other factors involved, let me know.
You can write JavaScript code that request a url using window.location.href in click hadler.
window.location.href="http://example.com";
Ok this was my solution but thank you also for your solution Jeff Ryan, this worked also.
<script language="javascript">
function buttons(str)
{
document.getElementById("txtHint").innerHTML = str;
if (document.f1.users.options[1].selected){
document.getElementById("txtHint").innerHTML ="<?php echo $mulmov; ?>";
document.messages.action = document.getElementById("txtHint").innerHTML;
}
else if (document.f1.users.options[2].selected){
document.getElementById("txtHint").innerHTML ="<?php echo $mulmov2; ?>";
document.messages.action = document.getElementById("txtHint").innerHTML;
}
}
function submit_mes(str)
{
document.messages.submit();
}
</script>
<form name="f1">
<select name="users" onChange="buttons(this.value)">
<option value="">Select a folder:</option>
<option value="Quotes">Quotes</option>
<option value="Projects">Projects</option>
<input type="button" value="Move" onClick="submit_mes(this.value)">
</select>
</form>
<div id="txtHint"><b>Folder will be listed here.</b></div>