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.
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.
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 working in CodeIgniter and I am trying to spit out all of the items I have in a table and order them as they should be using the dropdown. I want it to happen without page reload and without submit buttons, so I am using this jQuery function to make immediately react, when it is changed:
$(document).ready(function() {
$(".order-by-select").click(function() {var orderValue = this.value;
$.post("<?php echo base_url() ?>welcome/index", {val: orderValue}, function(data) {
alert(data);
});
});
Inside you can see the $.post method, with wich I am trying to send the data to php script (orderValue).
After that, I am getting an alert (not even sure, why do I need it (Maybe to check if everything is ok there))
In PHP, I am receiving the chosen select option and assigning a variable ($data['people']) to the results of MySQL query (that is placed in the model) to be able to access it withing the view. This - $_POST['val'] represents, how can I order the list (select * from people order by $theorder" ($theother is just a variable inside the query function. It recieves the value of $_POST['val'])).
if(isset($_POST['val'])) {
$data['people'] = $this->database->listPeople($_POST['val']);
exit;
}
After that I recieve this variable in the view and I am running foreach loop to take different parts of the array(name of the person, his age, etc..) and placing it in the way they should be.
The problem is - if I do that without ajax, when I have static order by value - everything works fine. I did not mean that was the problem :D, the problem basically is that is doesn't work with ajax... I was trying to recieve the array in the js callback and create a layout using
$.each(eval(data), function() {
$('#container').text('<div>' + eval(res).name + '</div>');
});
But that was also a failure...
How should I organize and create my code to make everything work properly?
I am kinda new to Ajax, so I hope I'll really learn how to do that from you guys. I already searched through the whole internet and have seen a lot of ajax tutorials and other kind of material (e. g. StackOverflow), but I still can't get, how can I do all of that in my particular situation. I have wasted already about 12 hours trying to solve the problem and couldn't do that, so I hope You will tell me if there is any useful salvation.
Thank you for your consideration.
Hi the skinny is you need 3 parts to make ajax work,
serverside code to generate the page
ajax ( clientside ) to make the call and respond
seperate serverside to receive it.
Also it will be easier to replace the table completely then to pick out elements. But that is up to you.
So say we have the page with our ajax call
<script type="text/javascript" >
$(document).ready(function() {
$(".order-by-select").click(function() {var orderValue = this.value;
$.post("<?php echo base_url() ?>welcome/index", {val: orderValue}, function(data) {
alert(data);
});
});
</script>
Now you seem to have some json response I'll assume you get this from the alert above;
[{"id":"1","name":"Nick","age":"18"},{"id":"2","name":"John","age":"23"}]
I'll also assume that this comes from something like
echo json_encode( array( array('id'=>1, ...), array('id'=>2 ...) .. );
It's important before doing the echo that you tell the server that this is json, you do this using a header, but you cannot output anything before the header, and after the json header all output must be in the json format or it wont work, it's like telling the browser that this is html, or an image etc. what the content is.
Header("Content-Type: application/json");
echo json_encode( ....
You can get away without doing this sometimes, but often you'll need to use eval or something, by telling the browser its json you don't need that. Now doing an alert is great and all but if you see the string data [{"id": .. your header is wrong, you should get something like [object] when you do the alert.
No once we have a factual Json object we can make use of all that wonderful data
<script type="text/javascript" >
$(document).ready(function() {
$(".order-by-select").click(function() {var orderValue = this.value;
$.post("<?php echo base_url() ?>welcome/index", {val: orderValue}, function(data) {
$.each(data, function(i,v){
alert(v.id);
alert(v.name);
});
});
});
</script>
This should loop through all the data and do 2 alerts, first the id then the name, right. Next it's a simple matter of replacing the content using .text() or .append()
<script type="text/javascript" >
$(document).ready(function() {
$(".order-by-select").click(function() {var orderValue = this.value;
$.post("<?php echo base_url() ?>welcome/index", {val: orderValue}, function(data) {
$.each(data, function(i,v){
$('#test').append('<p>'+v.id+'</p>');
});
});
});
</script>
<p id="test" ></p>
I am not sure if this is the best way to do it, but I have a button that when pressed it call a onClick JS function and it passed two parameters. I want to save those two parameters on a php session, then load another page and use those values.
So, I know that if I use something like this on PAGE !:
<?php
session_start();
$message1 = "A message";
$message2 = "Another message";
$_SESSION['routineName'] = $message1;
$_SESSION['dayName'] = $message2;
?>
I can go to PAGE 2, and by using $_SESSION['routineName'] I can use that info.
So, on PAGE 1 I have that code inside the function that is called with my onClick:
function trackIt(routine, dayName)
{
<?php
session_start();
$message1 = "A message";
$message2 = "Another message";
$_SESSION['routineName'] = $message1;
$_SESSION['dayName'] = $message2;
?>
}
I tried things like:
function trackIt(routine, dayName)
{
<?php
session_start();
$_SESSION['routineName'] = ?> routine; <?php
$_SESSION['dayName'] = $message2;
?>
}
and others, but nothing works.
And this is how I am calling the onClick (trackIt) function:
echo('<td colspan="3" style="background-color:#005673; text-align:right; padding: 4px 0px;">
<button class="btnTrack" onClick="trackIt(\'' . $name . '\' , \'' . $nameday1 . '\')" >Track It!</button></td>');
What I want to do is to save both, routine and dayName, into the session.
Is it possible to save JS variables/parameters into PHP Session?
PS: I am using Wordpress.
Thanks!
The PHP code you put in your files is not executed at Javascript run time, it is executed even before the page gets sent to the client. So you can't access $_SESSION from anywhere within your content, you need to do that from Wordpress's code. Usually this is done via a plugin.
You need to pass your Javascript variables to a server side PHP. As #Grasshopper said, the best (or at least most maintainable way) is through AJAX:
// This is your JAVASCRIPT trackit function
function trackIt(routine, day) {
$.post(
'/wp-setvar.php',
{
routine : routine,
day : day
}, // You can add as many variables as you want (well, within reason)
function success(data) {
// Here we should receive, given the code below, an object
// such that data.result is a string saying "OK".
// Just in case you need to get back something from the server PHP.
// Otherwise just leave this function out.
}
);
};
On the server, you need to create a specific file to accept the incoming variables (it would be best if you did this from a plugin, in order not to add files outside the installation: such practices are frowned upon by security scanners such as WordFence). This here below is a butcher's solution.
<?php /** This is wp-setvar.php */
/** Set up WordPress environment, just in case */
require_once( dirname( __FILE__ ) . '/wp-load.php' );
session_id() || session_start();
nocache_headers();
// DO NOT, FOR ANY REASON, ACCESS DIRECTLY $_SESSION
// ONLY USE A VARIABLE WITHIN $_SESSION (here, "ajjx")
// OTHERWISE THIS MAY ALLOW ANYONE TO TAKE CONTROL OF YOUR INSTALLATION.
$_SESSION['ajjx'] = $_POST;
Header('Content-Type: application/json;charset=utf8');
die(json_encode(array(
'result' => 'OK', // This in case you want to return something to the caller
)));
Now whenever you need the session-saved variable, e.g. "routine", you put
<?php
...
$value = '';
if (array_key_exists('ajjx', $_SESSION)) {
if (array_key_exists('routine', $_SESSION['ajjx']) {
$value = $_SESSION['ajjx']['routine'];
}
}
Or you can define a function in your plugin,
function ajjx($varname, $default = '') {
if (array_key_exists('ajjx', $_SESSION)) {
if (array_key_exists($varname, $_SESSION['ajjx']) {
return $_SESSION['ajjx'][$varname];
}
}
return $default;
}
Then you just:
<?php print ajjx('routine', 'none!'); ?><!-- will print routine, or "none!" -->
or
<?php print ajjx('routine'); ?><!-- will print nothing if routine isn't defined -->
An even more butcherful solution is to add the function definition above within wp-config.php itself. Then it will be available everywhere in Wordpress. Provided you have access to wp-config.php. Also, backup wp-config first and use a full FTP client to do it; do not use a Wordpress plugin to edit it, since if wp-config crashes, the plugin may crash too... and you'll find yourself in a my-can-opener-is-locked-within-a-can situation.
If you don't feel comfortable with some of the above, it's best if you do nothing. Or practice first on an expendable Wordpress installation that you can reinstall easily.
I am sure there are a number of articles covering this topic, but every piece of code I try just doesn't seem to work. If this has been answered somewhere else already, I am sorry that I could not find it.
I am trying to create a live search that displays all data in my table until someone starts typing in an input field. As soon as they start typing a key, I want to run a select query on my table to narrow the results if any of the columns contain the string that is currently being typed (kind of like how google starts showing you results as you type in the search bar).
My code seems to work up until I try to use either $.get or $.post to interact with my php file that runs the MySQL search. I am kind of new to web development and have been teaching myself as I go along, but this one has stumped me for 2 days now. Here is the code I currently have (although I have tried about 20 different versions):
jQuery:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script>
document.getElementById("search").onkeyup(searchScript());
function searchScript(){
var search = $("#search").val();
if(search==""){
return;
}
else{
$.get("resultspage.php",{search : search},function(result){
$("#results").html(result);
}});
}
</script>
<table id="results">
<?php
<...var assignments storing my db login data...>
$con=mysqli_connect($host,$username,$password,$database);
$sql="SELECT * FROM Registration";
if(mysqli_query($con,$sql)){
$result=mysqli_query($con,$sql);
}
else{
echo "error: " . mysqli_error($con);
}
while($row=mysqli_fetch_array($result))
{
<...code that displays the results...>
?>
</table>
My PHP file
$search=$_GET['search'];
<...variables storing log in data...>
$con=mysqli_connect($host,$username,$password,$database);
$sql="SELECT * FROM Registration WHERE CONCAT(fName,lName,storeName,numLocations,primaryPhone,secondPhone,email,products) LIKE %$search%";
if(mysqli_query($con,$sql)){
$result=mysqli_query($con,$sql);
}
else{
echo "error: " . mysqli_error($con);
}
while($row=mysqli_fetch_array($result))
{
<...code that displays results....>
}
Any help would be much appreciated! Thank you.
Recognizing that jquery is another mountain to climb, I would still learn & use it for it's simplicity. Once the data has been retrieved from the server, use jquery to hide the values not starting with or containing the entered value (.match() below), instead of repeated calls to the server.
Not knowing the structure of your table, a framework you might try:
$( "#search" ).keyup(function() {
// Test search letter entry is working
alert( "Handler for .keyup() called." );
var s = $("#search").attr("value"); // Typed in letter
// Pass an array of table contents
// there are a couple ways you could approach the 'gathering' of table items...
$(".individual-item-class").each(function(index, element) {
if (!element.match(/s/))
$(element:parent).css("display","none");
else
$(element:parent).css("display","table-row")
}):
});
This code will not get you off the ground, but pointed in a direction.
You can learn about selectors and a few jquery functions. Used here are each(), attr() and css().