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.
Related
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 don't know why I can't figure out a way to do this... This is basic programming logic. For some reason, my mind is just not working right today though. I have a page that loads and runs some javascript. When the page firsdt loads, the javascript needs to run using a default variable, however when a user clicks a link on the page, a PHP variable is set which gets sent to the javascript side of things changing the outcome of the javascript if statement. For some reason though, I just cant figure out how to get this to work. Please help.
<?php
$username = $_POST['username'];
?>
<script type="text/javascript">
// Change the username
var phpusername = "<?php echo $username; ?>";
if(phpusername == (undefined || null)) {
(This is where the default condition code will go)
} else {
(This is where code will run when user updates username)
}
</script>
There is a little more to this story as to why I am doing things this way (Using both PHP and Javascript), so please resist offering radically different solutions. There is a LOT more to this puzzle not shown here, however the rest of the puzzle does not necessarily effect the functionality of this part.
Thanks!
<?php
$username = isset($_POST['username'])?$_POST['username']:''; // set fallback value
?>
<script type="text/javascript">
// Change the username
var phpusername = '<?php echo $username; ?>';
if(phpusername == '') { // check if empty
(This is where the default condition code will go)
} else {
(This is where code will run when user updates username)
}
</script>
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.
I've dug deep for this one and can't seem to locate the answer, most answers will show you how to set and retrieve cookies within a language, but not cross language.
I need to pass a php array into a cookie and then retrieve the contents on another page with jquery so that I can dynamically set the options on a dropdown menu. (For a bootstrap dropdown menu, not a standard select dropdown) I have echoed out the php array to confirm it is present and it is.
I am using the jquery cookie plugin.
PHP snippet:
while ($row = mysql_fetch_assoc($result)) {
//Get Dropdown options
$wnDropdown[] = '<li value=' . $row['id'] . '>' . $row['name'] . '</li>';
} //end while
mysql_close();
} //end inner if
} //end else
//Cookie needed
setcookie("wnDropdown", json_encode($wnDropdown));
jQuery:
$(document).ready(function() {
var result = JSON.parse($.cookie('wnDropdown'));
alert(result);
});
The result alerted returns 'null'.
What am I missing?
If more information is needed, let me know.
There are some points which i want you to check
Make sure cookie plugin is loaded , best to load it after jquery.
Now regarding whitespaces before setcookie , much of this depends on you buffering setting if you have output buffering on then you can put anything or echo wherever and wherever you want and cookie header will still be sent but if its "Off" any <script> <style> <html> in short anything that comes before your posted php code is likely to cause problems .Check in your php.ini output_buffering=value if value is not "Off" and rather some number then you are clear here ; note that whitespaces inside <?php ?> don't matter just display function like echo,print_r etc do if they come before setcookie().
Also check the scope of $wnDropdownmake sure it's global and exists with some value when you call setcookie.
I am new to web development and I want my site to have a drop-down menu that will change the language of my site.I want a solution that will not require me to create a whole new html of the new site. I also want a way to make an input field that will ask users to add a number and then it will automatically add a word after the number.
Perhaps this maybe of some use to you - http://code.google.com/p/jquery-translate/.
Not sure what the second part of the sentence is but a somewhat easy way of doing this is server-side scripting. For example, if you are using PHP, I would recommend you echo the a variable instead of actually typing the contents in the place it belongs. Instead, store the content in a database and then load the content from a database depending on what language is selected (store this a session variable), store it in the variable and when the variable is echoed, bam.
Create in PHP by using $_GET[l];
<?php
if($_GET[l]=='en')
{
echo 'Welcome';
}
else if($_GET[l]=='sk')
{
echo 'Vítajte';
}
else if($_GET[l]=='de')
{
echo 'Wilkommen';
}
else
{
echo ''; //Here set your default language. For example if is not set- automatically to english
}
?>
Menu:
<?php
if(isset($_GET[topic]))
{
//This is code, if you use another $_GET[...]
//Without this, page will crash ,while it shows another thing
echo 'English';
echo 'Slovensky';
echo 'Deutsch';
//?l=lang changes to &l=lang
}
else
{
//Link with normal ?l=lang, cause page does not use another $_GET[...]
echo 'English';
echo 'Slovensky';
echo 'Deutsch';
}
?>