Thank in advanced,
I was looking at creating a linked dropdown menu and found tutorial/code online
I have used this code twice to create lmsdropdown.php and clubdropdown.php. I am able to store the values from the lmsdropdown form is a session and echo them to clubdropdown (just for verification that values are present).
lmsdropdown is a php include within members.php and clubdropdown is an include in members2.php.
When I select a value on clubdropdown the page refreshes to populate the 2nd dropdown box and this results in my session data being cleared.
I am new to PHP/Javascript so the answer may be very obvious but this has had me stumped for a few days now. Any help would be very much appreciated.
Below is a merge of two snippets members2.php, that has taken the output of lmsdropdown and stored output in sessions.
clubdropdown shows the java code and also the echo session statements
I am able to correctly echo the session data however the javascript seems to remove this when building dropdown 2.
members.php session data
<?php
session_start();
$_SESSION['lms'] = $_POST['lms'];
$_SESSION['week'] = $_POST['week'];
if (!isset($_SESSION['usr_lvl']) or ($_SESSION['usr_lvl'] != 0)) {
header("Location: login.php");
exit();
}
?>
clubdropdown output of session data
<SCRIPT language=JavaScript>
function reload(form) {
var val = form.lge.options[form.lge.options.selectedIndex].value;
self.location = 'members-page2.php?lge=' + val;
}
</script>
</head>
<body>
<?php
$usr = $_SESSION['usr_id'];
#$lge=$_GET['lge']; // Use this line or below line if register_global is off
if(strlen($lge) > 0 and !is_numeric($lge)){ // to check if $lge is numeric data or not.
echo "Data Error";
exit;
}
$usr = $_SESSION['usr_id'];
$lms=$_SESSION['lms'];
$week=$_SESSION['week'];
echo "<br>Value of \$week = $week<br>Value of \$lms = $lms <br>Value of \$usr = $usr";
The image below shows the session variables outputted to clubdropdown that is included in members2.php
clubdropdown with variables shown
This image shows the errors after a selection is made from th 1st dropdown.
Error after list refresh
From some of the answers to similar questions on here I assume the error is because the post data is being overwritten/removed on refresh but I thought that's what the session was for?
Any input is greatly received thank you.
You are getting the values from $_POST, which the second time you run the page is absent. You need to add an If(isset($_POST['lms'])){ $_SESSION['lms'] = $_POST['lms']; } so that it is skipped if the $_POST value isn't present.
Currently, your $_SESSION variables are still there, but are being replaced with empty $_POST values.
I suspect you might be better off using an AJAX call to populate your dropdown list.
Related
Below is my code snippet:
setTimeout(function(){
var backed = localStorage.getItem("backed");
if(backed == "goback"){
var order = $("#plan").val();
<?php if(isset($_GET['frm'])){ ?>
$('select[id="type"] option:eq(0)').prop('selected',1);
$('select[id="plan"] option:eq(0)').prop('selected',1);
<?php
$name = $_GET['name'];
$update = $_GET['data'];
$type = $_GET['type'];
?>
// Filter One
$('select[id="data"] option:eq(0)').prop('selected',<?= $update ?>);
$('select[id="type"] option:eq(0)').prop('selected',<?= $type ?>);
$('select[id="plan"] option:eq(0)').find('option[value="'+order+'"]').attr('selected','selected').trigger('change');
<?php
} else { ?>
// Render with saved history
$('select[id="plan"] option:eq(0)').find('option[value="'+order+'"]').attr('selected','selected').trigger('change');
<?php
}
?>
}
}, 3000);
I designed this logic to pull values from a GET string and populate a JS function. Once done, using jQuery to populate a form with those values and then trigger a drop down selection; which on the front-end triggers a rendering of a data table with those pre-populated form values.
It worked for the most part, with one exception. If the value I'm pre-populating, matches the value that's already there in the drop down, the trigger('change') doesn't take.
To combat that, I thought to set default values (You'll see after the IF statement), and then triggering the change after the values are set.
I also attempted populating the form and manually callingthe function that runs on change. This didn't work either.
The above approach isn't my preference as I'd much rather work with the controller and that performs the original data pull; but modifying that process isn't an option for me at the moment. So I'm limited to the front-end fix. Can anyone advise on the best approach to get the trigger firing after the default is set?
Thanks in advance.
I am building a website for a school-project. I have been programming in PHP for about a year now, and javascript shouldn't be that much of a problem either.
However, I ran into a problem a couple of days ago. I have a "warning/notification" bar under my navbar. There is two buttons, one where you close the notification and one where you get redirected to read more about it.
If you click the close button, I want to make an AJAX call to the same file, where I have PHP code that will detect the call and then change a SESSION variable, so the notification doesn't show up again regardless of which file you are on.
This however, does not seem to work no matter how many approaches I have tried. I've had enough of this struggle and would greatly appreciate any help from this wonderful community.
This by the way is all in the same file.
Here's the AJAX code:
$("#close_warning").click(function(){
var info = "close";
$.ajax({
type:"POST",
url:"navbar.php",
data: info
});
});
And here's the PHP code (that prints out the HTML):
<?php
require "includes/database.php";
$sql = "SELECT * FROM posts WHERE (post_sort = 'homepage' OR post_sort = 'everywhere') AND post_type = 'warning'";
$result = mysqli_query($conn, $sql);
$resultCheck = mysqli_num_rows($result);
if($_SESSION["closed_notification"] == 'no') {
if($resultCheck >= 1) {
while($row = mysqli_fetch_assoc($result)) {
$post_header = $row["header"];
$post_content = $row["post_content"];
$post_index = $row["post_index"];
echo '<div class="nav_bottom_holder_warning">
<div class="navbar_lower_container">
<p>'.$post_header.'</p>
<button class="btn" id="close_warning">Stäng</button>
<button class="btn" id="show_warning">Visa inlägg</button>
</div>
</div>';
}
}
}
?>
Last but not least, the code that is responsible for changing the actual SESSION:
<?php
$_SESSION["closed_notification"] = "no";
if(isset($_POST["info"])) {
$_SESSION["closed_notification"] = "yes";
}
?>
I have tried numerous approaches to this problem, this is just one of them. At this point I am just clueless of how to solve it, thank you.
EDIT: I have already included this file in another file that contains a "session_start()" command. So using that in this file would be no help.
First of all there is no session_start(); on the first line so it will give you an error for the Session Variable.
Secondly update your ajax code to this:
$("#close_warning").click(function(){
var info = "close";
$.ajax({
url: 'navbar.php',
type: 'post',
data: {info:info}
});
});
It basically means that data:{name1:variable2}
Here you are giving the data from js variable(variable2) 'info' to php as info(name ==> that we generally set the input attribute) so in php you can access it as $_POST['info'];.
And lastly you gave the js variable value 'close' and you just checked whether the variable is set while changing the session variable.
Change it to actually checking the value which is better and clear when others read your code.
Summary:
Change data: info to data:{info:info}
Just use Javascript local storage or session storage. I guess it is not important for the server to know if a user has closed the notification yet or not.
$("#close_warning").click(function(){
// close the notification
$("#notification").hide();
// set 'closed' flag in local storage
storage.setItem('closed', 1);
});
Have javascript hide the notification, if the 'closed' flag is set.
if (storage.getItem('closed')) {
$("#notification").hide();
}
I created a session in php and the value of that session is from angularjs. I created a function that has a parameter. And every time I click on a button, the function will execute and the parameter of the function will send to php. What my problem is when I click the first button my php page will display the value of 18 and it is correct. Now when I go back to the buttons and click another then redirect to php page it doesn't echo the new value which is 20 and it still echo the last value which is 18.
$scope.sendval = function(id){
$http.post('page',{
'param': id
}).then(function(response){
//some codes...
});
};
page.php
session_start();
$data = json_decode(file_get_contents("php://input"));
$_SESSION['param'] = $data->param;
Display session
session_start();
echo $_SESSION['param'];
My problem is the value of the session remains the same. But when I refresh page, it updates. How to do it without page refresh? TIA!
What I've already tried and still not working:
session_destroy($_SESSION['param']);
// and
unset($_SESSION['param']);
$_SESSION['param'];
You must have placed the unset in the wrong place.
<?php
session_start();
$data = json_decode(file_get_contents("php://input"));
if (isset($_SESSION['param'])) {
unset($_SESSION['param']);
$_SESSION['param'] = $data->param;
}
else{
$_SESSION['param'] = $data->param;
}
?>
This question already has answers here:
How do I pass variables and data from PHP to JavaScript?
(19 answers)
Closed 6 years ago.
I have an html/php composite document that uses the login variable from a user. (This came from a separate php file on signin):
<html> Welcome <?php echo $login; ?> </html>
//Now when the user uses the chatbox, and clicks send, I would like to pass the data (inclusive of the username) from this html file to the .js so it can in turn pass onto another php file. (ps I tried the following but to no avail, as the .js file is external to the html/php composite):
$("#newMsgSend").click(function()//triggers script to send the message
{
$("#newMsgCnt").val(''); // clears the box when the user sends a message
var username = "<?php echo $login; ?>";
alert(username);
});
Your current code is likely introducing an XSS vulnerability. Instead, take advantage of the fact that valid JSON is valid JavaScript:
var username = <?php echo json_encode($login); ?>;
In some situations, it may also be better to use an XMLHttpRequest or WebSocket that requests the data from another URL (typically encoded as plain text, XML or JSON). One scenario for that would be notifying the user once new items have been added after the user loaded the webpage.
when the user logs in, create a session for that user and populate it with the data (such as username, email, phone number or whatever) from the database - as followings (assuming that the login is correct and authentic:
$_SESSION['user'] = $row; //where $row is the row of data returned from the db
Then whenever you want to access that information include the following at the top of the page:
session_start();
and then access the information such as
$userfirst_name=$_SESSION['user']['first_name'];
then your html will be something like:
<h1> Welcome <?php echo "$userfirst_name"; ?> </h1>
note that session start must be at the top of each page you are wanting to access the sessiobn variables. Then to clear the user details (such as when the user logs out you can use the following:
unset($_SESSION["user"]);
Thanks to both: Ivan Rodriguez Torres and phihag. I got a solution somewhere in the middle of both posts:
<input id="login" readonly type="text" <?PHP echo "value= '$login'/>"; ?>
Ivan's suggestion was somehow returning an "undefined" variable for me. The above works like a charm though. Hope its safe and doesnt lead to any problems.
Thanks again guys
I have a problem in confirmation message when the USER click CANCEL the value of $IsCanceled = "yes"
then when I click OK the value of `$IsCanceled = "no"..
The problem is, when I click the OK the value of $IsCanceled is still yes...
<?php
else { ?>
<script>
var myVar = "<?php echo $bldg[$i]; ?> station is already full. Do you want to save the other networks?";
if (confirm(myVar)) {
<?php $IsCanceled = "no";?>
} else {
<?php
$IsCanceled = "yes";
?>
}
</script>
<?php
}
//and so on...
I already traced everthing but its still "yes" the value..
Thanks
PHP and Javascript.
Two completely different languages used in various different tasks.
What you have written above tries to mix two languages, which if you were writing in any other environment you wouldn't even consider doing. The above script you have written, will run its PHP when on the server, and produce an output that is sent to the browser.
In your case, that will look something like:
<script>
var myVar = "i station is already full. Do you want to save the other networks?";
if (confirm(myVar)) {
} else {
}
</script>
That is the exact output of your code at the moment. If you want to navigate the user to "save to other networks", you would have to create a hidden HTML form, with an <input type="hidden" .. that can hold the answer you need. Then, with Javascript, you can show your confirmation dialog and populate the HTML form, submit it, and handle it again with PHP.
Think of it like Tennis. You cannot change the way you hit the ball, after already sending it to the opponent. In this case, you can program both sides and make them handle the tennis ball accordingly.
php is server side scripting it can not assigned without page refresh.
Use javascript(client side scripting) variable to assign yes or no
else
{
?>
<script>
var myVar = "<?php echo $bldg[$i]; ?> station is already full. Do you want to save the other networks?";
if (confirm(myVar)) {
IsCanceled = "no";
} else {
IsCanceled = "yes";
}
alert(IsCanceled);
</script>
<?php
}
If you want to do some logic at client side you need to use JS without PHP in it.
And if you need to do logic server side so you need to POST or GET to the server.
Just open your page as source right after it loaded and you will see, that in place where you put PHP condition will be nothing.
It's because PHP already done all it's work. Check $IsCanceled and show page to you.
ALSO note, that if you need to check instead of assign you need to use double equals sign instead one e.g. if($IsCanceled == 'no') will check if variable IsCanceled equals string 'no'. BUT if($IsCanceled = 'no') tells php to assign string 'no' to variable IsCanceled it will be TRUE always because it's assignment and result of assignment is TRUE