How can i pass a variable from one page to another? - javascript

I am creating a website, that has many pages. You can change the number of posts shown in each page through a drop down menu. My problem starts if i change the amount of posts move to the next page it comes back to default.
e.x default posts shown is 30, and then i change it to 40. The moment i change page it comes down to 30 again on the next page.
I have tried something like that but unfortunately doesn't work.
<form method="get" name="SkipPage">
<select name="results_no" onChange="document.forms['SkipPage'].submit()"> `
<?php
....
?>
</select>
</form>
$reults_no = isset($_GET['results_no']) ? $_GET['results_no'] : 30;

try to use hidden intput
<input type="hidden" name="myHiddenVar" value="<?php echo $myVar ?>"
Then you can use your var with $_POST["myHiddenVar"];
But if you want a persistent choice use sessions.
session_start(); on each page and access/edit your var with $_SESSION['myVar'];

If you want to make a user choice persistent, the usual solution is to save it in a cookie.
EDIT: or in SESSION but my point is that you don't have to pass the value as a GET parameter for each link followed by the user. You set it once and test if set on each page that need it.

Related

How to make an input value permanent in wordpress or work with global variables

I currently make my first Wordpress website using Java script snippets for a countdown that refreshes itself constantly and allows me to click a button once every 6 hours. So I managed that the time refreshes itself but I need one permanent variable that tells me if I already clicked the button or not (since it should work wether I refresh the page, go to another side or even log in with another user).
Basically I just want one variable that changes between 0 and 1.
I implemented a hidden input field and it works just fine as long as I stay on the side (refreshing the side works as well) but as soon as I change the page it sets the variable back. I tried to implement a global variable in the function.php of my theme (and a function as well) but it still doesn't work.
I tried it like this:
global $x;
echo $x;
And this:
function displayX() {
global $x;
$x = "0";
echo $x;
}
The thing is I don't want to set a value because the variable needs to be changeable any time.
That's my current html:
<input type="text" id="id1" value="<?php echo $x; ?>" <="" input="">
But it just doesn't work.
My second approach was to make the input field permanent (but updateable) - again this approach works as long as I don't change the side.
I tried it like this:
<span id="00">
<input type="text" id="id1">
</span>
Can anybody please help me? Also please specifiy where I have to set the global variable since there are so many function.php files.
THANK YOU!
Easiest way to do that is using of update_option and get_option.
update_option is for save data to database that will be permanent.
get_option is for fetching data from database.
<form method="post">
<input type="text" name="permanent" id="permanent" value="<?php echo get_option('permanent_data'); ?>"/>
<input type="submit" name="save" value="submit"/>
</form>
You can catch form data in backend using an action like this:
in functions.php
add_action('init','save_permanent');
function save_permanent(){
if(isset($_POST['save'])){
update_option('permanent_data', $_POST['permanent']);
}
}
Below code checks that if form is submitted:
if(isset($_POST['save'])){
update_option('permanent_data', $_POST['permanent']);
}
If form submitted it gets value of input text that named permanent
Mentioned code permanent the data in database as name of permanent_data
If you want to fetch stored data you just call get_option(option name) like this:
<?php echo get_option('permanent_data'); ?>
For first question you can do it in such way:
in functions.php
<?php
if(if(isset($_POST['save']))){
update_option('already_clicked', '1');
}
And for fetch stored data you can use:
<?php
if(get_option('already_clicked') == '1'){
//do somthing
}
?>

Use get_option in WordPress to create new JavaScript variable

So I've been building my first WordPress plugin, and I've of course hit some roadblocks. I first wrote all this code as a page template, but now I'm converting it to a plugin so I can use it across several sites.
It's essentially a contact form that creates a price quote based on user selection. When it was a template, I just hardcoded the values and made everything work with an external jQuery file. Now, I'm wanting to take user input from the plugin admin settings page and use that value to make calculations rather than the values I hardcoded.
Here's what I had before with the jQuery:
(function($) {
$(document).ready(function(){
$("#carpet_cleaning).change(function () {
var bedrooms = $("#carpet_cleaning").val();
/*-------CHANGE RATES HERE--------*/
var total = (bedrooms * 39);
var totalPrice = "$" + total;
$("#output1").text(totalPrice).fadeIn();
});
}(jQuery));
So basically I want to use user input from the plugin admin settings instead of hardcoding a 39. That way prices can vary depending on what price the user wants to set.
Here's my HTML for my admin settings:
<h2>Display Settings</h2>
<form method="post" action="options.php">
<?php settings_fields( 'my-plugin-settings-group' ); ?>
<?php do_settings_sections( 'my-plugin-settings-group' ); ?>
<fieldset>
<input type="text" size="3" name="carpet_cleaning_price" value="<?php echo esc_attr( get_option('carpet_cleaning_price') ); ?>" /><label>Carpet Cleaning Price Per Room</label>
</fieldset>
<?php submit_button('Save all changes', 'primary','submit', TRUE); ?>
</form>
I was under the impression that I could use get_option to store the user input. If that's the best way to do that, how could I access that value in my jQuery variable?
Ideally I'd want to do something like:
var sectionalCleaning = carpet_cleaning_price;
And then just use carpet_cleaning_price instead of 39, which would give me the user value.
Is there some way I can do this easily? I'm also going to have to do this on the backend using PHP so that someone can't adjust the values in their browser and the calculation happens on the server, so if you have a solution for that as well, I'm open to that. Go easy on me, I'm a new developer! Thank you.

global variable not displayed in div

I declare a variable at the beginning of my .js file:
var option="blabla";
On page 1.html I click on a link to page 2.html where I have
<script>document.write(option);</script>
No text is displayed on 2.html. When I refresh the browser while I am on 2.html I get undefined as an output.
What do I have to do to have the text displayed straight after I click the link?
Alternatively, how can I get the following code work to output strUrl on 2.html:
on 1.html I have a link:
<a href="2.html" onclick="function1("item")">
on 2.html I have a div:
<div id="display">document.write(strUrl);</div>
then I have in my .js file:
function1(searchitem)
{
strUrl = 'http://blabla.com/'
+ '?key=' + searchitem;
}
You try to create a Javascript variable on a page and then use it on another page. This is a more-or-less broad problem, since you want to maintain values across pages. First of all, you need to decide where is this value going to be defined and where is it going to be used. If this is more like a server-side variable, then you need to define it on server-side and then generate it into your Javascript code. If you are using PHP, then you can do it like this:
<script type="text/javascript>
var foo = '<?php echo $bar; ?>';
</script>
Naturally, you need to initialize $bar to be able to do that. If the variable should be a client-side variable, then you need to use localStorage, like this on 1.html:
localStorage.setItem("option", "blablabla");
and then load it on 2.html:
localStorage.getItem("option");
Or, if you need to use it both on server-side and client-side, then you can use a cookie for this purpose. Using cookies i slightly more complex, but my answer to another question should get you going.
Let's focus on the cause this did not work for you. A Javascript variable will cease to exist when the page is unloaded, so you will not be able to use its value after that. So, you need to persist it somehow, storing it either on the server or the computer where the browser is being run.
As a side-note, I should mention that you can use Javascript variables accross pages if you load some pages inside iframes of a page, but that is a different scenario.
This is what FORMS and AJAX were invented for. If your server has a PHP processor (virtually ALL of them do), then you can rename your .html files to .php and use a bit of PHP to accomplish your goal.
A web page ending with .PHP works exactly the same as one ending in .html, except that you can now add snippets of PHP code where desired. It is not necessary to have any PHP code, but if you have some it can do stuff.
Method One: FORMs
If you want to switch to page2.html and see a value sent from page1.html, you can use a FORM construct and post the data from page1 to page2:
page1.php
<form action="2.html" method="post">
<input name="option" type="text" />
<input type="submit" name="sub" value="Go" />
</form>
page2.php
<?php
$p1 = $_POST['option'];
?>
<div>On page1 of this website, you typed: <?php echo $p1; ?>. That's what you did.</div>
Note how a <form> uses the name= attribute for the name of the variable that is sent to the other side.
Example Two: The AJAX method
HTML:
<div id=nonForm">
<input id="option" type="text" />
<input type="button" id="myButt" value="Go" />
</div>
<div id="results"></div>
jQuery:
$('#myButt').click(function(){
var opt = $('#option').val();
$.ajax({
type: 'post',
url: 'page2.php',
data: 'option='+opt,
success: function(john){
if (d.length) alert(john); //display result from Page2 in a pop-up box
$('#results').html(john); //Or, display it right on the page
}
});
});
PAGE2.PHP -- The AJAX processor file
<?php
$opt = $_POST['option'];
//Now, you can do something with the data in $opt, and then send back a result
$rtn = 'Hey, you sent: ' .$opt;
echo $rtn;
The primary (and most important) difference between the two methods is that the FORM will change pages on you. The user will be sent from Page1 to Page2, and the screen will flash as this happens.
What's exciting about AJAX is it sends data to Page2, where Page2 can do something with it (for example, a database lookup), and then Page2 sends different data back to Page1. This new data can then be displayed on the page WITHOUT the page refreshing.
Here are a couple of very basic AJAX examples, to get you going:
AJAX request callback using jQuery

JQuery populating select box but after post options disappear

I have an SVG map. When someone clicks on a state say, "Kansas" it displays a form and populates the state select box with the state that was clicked on say, it's Kansas. Code - This is working fine. This code is in the head.
var itemval= '<option value="'+data.name+'">'+ stateData[data.name].fullName+'</option>';
$("#SelItem").html(itemval);
When the form is submitted and it posts back to the same page, I'm using
<form method="POST" action="theform.php" onsubmit="return validateForm(this);">
When the page post back to the same page the select box is empty. The select box is there but with no option.
I've searched on Google I found the code below plus a few similar ways but they don't work. I've used this code in the head and under the select but no luck.
var selectedVal = $("#SelItem").val();
$("#SelItem").val(selectedVal);
**HTML**
<select id="SelItem"><option></option></select>
I've been working on this for hours but can't seem to find a solution.
Can someone tell me how to keep the select value after the form has been submitted and returns to the same page?
When the page loads you need to check for the presence of your posted value, and if it's there pass the php value to either the javascript code to populate the select option, or use it directly in the html creating the select options.
First off, you should give your select a name attribute in the html so the value is passed into the $_POST array in php:
<select id="SelItem" name="SelItem">
Here's one way you can populate it in javascript (note this code relies on the var stateData being in the same scope):
$(document).ready(function(){
<?php if (!empty($_POST['SelItem'])): ?>
var posted_state = '<?php echo $_POST['SelItem'];?>';
if (stateData[posted_state] !== undefined) {
var itemval= '<option value="'+posted_state+'" selected>'+ stateData[posted_state].fullName+'</option>';
$("#SelItem").html(itemval);
}
<?php endif; ?>
});
EDIT: An alternative to the above would be to put it in the html for the select tag:
<select id="SelItem" name="SelItem">
<?php if (!empty($_POST['SelItem'])): ?>
<option value="<?php echo $_POST['SelItem'];?>" selected>
<?php echo $_POST['SelItem']; // this would be better if you can replace it with fullname ?>
</option>
<?php else: ?>
<option></option>
<?php endif; ?>
</select>
Note this method has a couple issues as it's written. First off, the option text in this example won't be the state full name but the abbreviation. Next, you shouldn't trust the contents of $_POST because a malicious user can easily change it to a value you didn't intend it to be. It would be better to validate the value of $_POST['SelItem'] in your php code that handles the post to make sure it is actually one of the correct values before using it. That is why in the previous example I did the check if (stateData[posted_state] !== undefined) before attempting to add the value to your select.
EDIT:
To provide the state fullname from php you need an array of states defined on the php side also (I only see it in your javascript code which is client side).
So in php if you have something like:
$states = array(
'AK' => 'Alaska',
'AL' => 'Alabama',
// etc...
);
Then you can use the posted state abbreviation to get the fullname:
if (array_key_exists($_POST['SelItem'], $states))
$fullname = $states[$_POST['SelItem']];

Cookie not set until a second refresh

I have a form on page 1:
<form method="post" action="request-form">
<input
type="text"
id="amzQry"
name="item"
placeholder="What do you need?"
autocomplete="on"
/>
<input
id="autocomplete"
name="destination"
placeholder="where? (e.g. Buenos Aires)"
onfocus="geolocate()"
type="text"
required=""
aria-required="true"
autocomplete="off"
/>
<button type="submit" value="">
Submit
</button>
</form>
I want this information to be held in a persistent way so that even if a user subsequently logs in (to joomla in this case) the cookie data is persistent and can be called. That is why i have used cookies rather than sessions in this case. Correct me if this is not the right way of doing this.
I have some code to set and retrieve the cookie on page 2:
<?php
$itemcookie = $_POST['item'];
$detsinationcookie = $_POST['destination'];
setcookie("itemcookie", $itemcookie, strtotime('+30 days'));
setcookie("destinationcookie", $detsinationcookie, strtotime('+30 days'));
?>
But the cookie data is not appearing on the second page when it loads after form submit. If I refresh the second page the data appears in the right places, i.e. where I have called it with e.g.
<?php
echo $_COOKIE["itemcookie"];
?>
How to get the cookie data available immediately on page 2?
You can't.
If you check the manual:
Once the cookies have been set, they can be accessed on the next page load with the $_COOKIE or $HTTP_COOKIE_VARS arrays.
^^^^^^^^^^^^^^
This means your cookies will not be available on the page / script where you set them.
You could use another variable to show the value though, for example like:
$itemcookie_value = isset($_POST['item']) ? $_POST['item'] : $_COOKIE["itemcookie"];
Apparently you have some output before you call setcookie()
If you have some output (even one single space character) BEFORE session_start(), setcookie() or, say, header(), the browser will not recognize the cookie and they won't be available right after the script starts.
You can.
All you have to do is set the cookie with a AJAX request that way the cookie is set while you are still on the page then when you refresh the page ONE time the cookie will be available to you.

Categories

Resources