Im trying to pass a value from one page for a product to another page for the cart.
I've tried a few different options but haven't managed to come up with any solution.
I'm new to html and javascript so need a simple solution if thats possible so that I can understand.
Product Page
<label for="exampleFormControlSelect1">Example select</label>
<div>
<select class="form-control" id="Selected">
<option value='1'>1</option>
<option value='2'>2</option>
<option value='3'>3</option>
<option value='4'>4</option>
<option value='5'>5</option>
</select>
</div>
<button id='btn' type="button" class="btn btn-secondary">Add To Cart</button>
<script type="text/javascript">
var value=0;
function send_selected(){
var selector = document.getElementById('Selected');
var value = selector[selector.selectedIndex].value;
sessionStorage.setItem(value);
}
document.getElementById('btn').addEventListener('click',send_selected);
</script>
Cart page
<script type="text/javascript">
var value = sessionStorage.getItem("value");
document.getElementById('display').innerHTML = value;
</script>
<body>
<div id="display"></div>
</body>
I would need to value from the drop down to be passed to the cart page to work out the value for all the users products selected.
You need to add two arguments to sessionStorage: key and value. Something like this:
sessionStorage.setItem("selectValue", value);
Also, as far as I know if you work with local html files opened like path/cart.html in the browser, the sessionStorage can't help you; it's scope is limited to the page. If you serve them through localhost, you'll be alright.
If this pages have different url, you can do it with query params: https://en.wikipedia.org/wiki/Query_string
By Browser Storage Method :
As mentioned by #Ferenc, the setItem method of session storage takes two parameters.
sessionStorage.setItem("selectedItem","value");
or you can use
sessionStorage["selectedItem"] = "value";
And to retrieve the value anywhere else in the browser you can either use the getItem() method or you can go with the array like value access approach i.e.
var value = sessionStorage["selected"];
But I would suggest you go with localStorage instead of sessionStorage, Because of it's larger scope than the sessionStorage scope.
You can read difference b/w session storage and local storage here.
Note: You can check for errors in your javascript code(Which now occurs when you call the getItem method with a single parameter ) by looking in the browser console.
By Query Parameters:
Well, this is not a recommended method if you are not using any server-side language. i.e. Java, PHP etc.
In this case, you append the query string in url. i.e.
http://www.url.com?value=selected
To Read how to access query parameters by using javascript refer to this question.
It worked for me to add to the 1st HTML file:
where_from = document.getElementById("where_from").value;
sessionStorage.setItem("pass_to_other_form", where_from);
and then to the 2nd HTML file:
var from_other = sessionStorage.getItem("pass_to_other_form");
Related
I running in some issues with my code below. I have achieved to create a new element and add it to the Option list. Now a whenever i refresh the page the new element will disappear from the list.I am not familiar how cookies or session works in JavaScript. But how could i store those element and whenever i create a new element to be able to be in the Option list even after refreshing. Sorry for my English , and thank you for the help in advance. My code is below as you can see.
<select name="name" id="name">
<option value="burim" class="someName">burim</option>
<option value="eliot" class="someName">eliot</option>
<option value="saska" class="someName">saska</option>
</select>
<br><br>
<input type="text" id="add">
<input type="submit" name="submit" value="ADD list" id="btn">
<p class="output"></p>
<script>
var btn=document.getElementById("btn");
btn.onclick=function(){
var n =document.getElementById("name");
var list=document.getElementById("add").value;
var listArray={};
var newOption=document.createElement("option");
listArray=n;
newOption.className="someName";
newOption.innerHTML=list;
newOption.value=list;
n.appendChild(newOption);
}
</script>
There is three ( main ) way to store client side data in Javascript.
The cookies are used to store data that is accessible to the server, ex: JWT authentication token.
The other two are Session storage and local storage. I've never learn the difference between the two but here is a good question about it.
In your case, I would suggest using localStorage. It is very easy to use and will be available until clear programmatically or by the user.
You can add data to the localStorage using
window.localStorage.setItem('key', value)
and retreive it using.
window.localStorage.getItem('key')
You should only keep minimum data in the localStorage, don't store your HTML. Store only enough data to rebuild it once you need your information.
I am trying to retrieve simple javascript variable (which is written to a File Systems Object) from a website which is served by an apache host on my ubuntu laptop.
So I have the function that writes the variable set up as follows:
<script type ="text/javascript">
function WriteToFile(passForm) {
set fso = CreateObject("Scripting.FileSystemObject");
set s = fso.CreateTextFile("/home/lex/Downloads/goal.txt", true);
s.writeline(document.passForm);
s.Close();
}
</script>
and the section that takes the user input from the html website is
<div id="bot-right">
<form onsubmit="WriteToFile(this['goal'].value)">
<a align = "left"> <b><Strong>Enter a Goal name</Strong></b></a><br>
<input type="text" name="goal"> <br>
<input type="submit" value="Send Zeus">
<br>
</form>
</div>
For some reason, when I type in variable names to the form on the website, the file goal.txt gets created in the directory, /home/lex/Downloads/, but nothing gets written to it.
I also noticed that when I delete the goal.txt file and rewrite the variable from the html website, the file doesn't always get created.
I am not a JavaScript person and I am at a loss as to what I may need to fix this.
My intention is to get the variable written to the text file and have a processing c++ file process the variable.
Would someone be kind enough to lend an insight?
Thanks!
one way to do it is just calling the function without parameters and just getting the input value like this:
adding and id or a class to your input to get that specific value:
document.getElementById('goal').value
document.getElementByClass('goal').value
Or getting the value by name:
document.querySelector('[name="goal"]').value;
EDIT1
You could add a console.log to check if the value is beign passed correctly like this:
var inputValue = document.querySelector('[name="goal"]').value;
console.log(inputValue);
And if the value is being passed then the problem is your writeline or in the creation of the document
EDIT2
I just tested it and retrieving the value works just fine, so the problem must be in your document writing method, please check this documentation it can help you and i think is a better solution:
http://www.html5rocks.com/en/tutorials/file/filesystem/
So this is what i have in html:
<p><br><form name="edit" method="post">
<div><select name="Edi" id ="Edi" >
<option selected="selected">Select</option>
<option value="1.php">Apple</option>
<option value="1.php">Bannana</option>
<option value="2.php">Carrot</option>
</select>
<input onclick="return Edit();" type="submit" value="Edit"/></div>
</form>
here is the corresponding javascript:
function Edit(){
if(document.forms['edit'].Edi.value == "Select")
{
alert("Please Select Edit Field");
return false;
}
else
{
window.open(Edi.options[Edi.selectedIndex].value);
return true;
}
}
Here is my problem. As you can see both my option Apple, and Bannana open the same php page. I want that. But i also want a variable in PHP that can store Apple/Bannana depending which was chosen in dropdown.
I tried this in PHP and it did not work.
$Table = $_POST['Edi'];
I know i can create a different PHP page for Apple(1.php) and Bannana(3.php). But in my program creating a page will just be duplicated code. (Apple and bannana just decide which table to store in). Also, i might be adding more options in the future, so i dont want to keep copying code.
What i came up with is putting the variable in javascript, but then tranfering to PHP is not possible. So I decided with creating extra layer rather than creating copied pages. (1 selected-shows apple, bananna) (2 selected-shows carrot). I can do this.
But is this the most efficient way of doing this?
You can use PHP's $_GET array to access URL parameters.
For example:
<option value="1.php?table=apple">Apple</option>
<option value="1.php?table=banana">Banana</option>
And your PHP:
$table = $_GET['table'];
If the variable could be missing, you can provide a default value by using PHP's ternary operator:
$table = isset($_GET['table']) ? $_GET['table'] : 'apple';
I am new to PHP and hope someone can help me with this.
I have a page (index.php) where users can select a language.
If no language is selected than the page URL is just index.php which defaults to English.
If they select a language than the page gets reload and the variable ?lang=xy is added to the URL which defines the page language.
E.g. for German the page URL would then be index.php?lang=de .
So far everything works as intended.
Now I have a navbar on the index page that allows to navigate to other pages which are all saved as separate php files (like page1.php, page2.php, page3.php etc.).
How can I manage that if someone has selected a language on the index page and then navigates to another page that the language variable is passed along to all other pages ?
E.g. for German the other pages shoud be page1.php?lang=de, page2.php?lang=de, page3.php?lang=de etc.
I know I can use $_GET["lang"] on each page to fetch the variable but couldn't find a way to pass this on from the index page to other pages using PHP or JavaScript/jQuery, ideally in a way that I can set this more general instead of separately for every single link.
Note:
I am using undordered lists with standard links to create my navbar, e.g.:
<li>Page1</li>
Can someone help me with this ?
Many thanks in advance.
You can use cookies to do so
setcookie(name, value, expire, path, domain, secure, httponly);
i.e.:
setcookie('language', 'german', 60000,"/");
and then check this wherever with
$_COOKIE["language"]
http://php.net/manual/en/features.cookies.php reference
you can use sessions to pass variables to any page,it's more secure than cookies as it's a server side,
example:
After Posting Data:
<?php
session_start();
if(isset($_POST)){
$var_name=$this->db->real_escape_string($_POST['input_name']);
$_SESSION['var1_sess']=true;
$_SESSION['var1_sess']=$var_name;
}
?>
note:session_start() must be in the first line of the file.
If you are using to select languages, just add onchange event to then submit the form to index.php
<form action="index.php">
<select name="lang" onchange="javascript:this.form.submit()">
<option value="en">English</option>
<option value="xy">XY</option>
</select>
</form>
and in the same page
<?php
$lang = $_GET['lang'];
if(empty($lang)){
$lang = "en";
}
?>
Then pass the $lang to where you want to
<li>Page1</li>
df2 = pd.DataFrame(np.random.randn(5, 10)).to_html()
myPage = """
<html>
<body>
<h2> Website </h2>
<form action="/helloworld" method="get">
<select id = "options">
<option value="">""</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select>
</form>
<button type="button" onclick="showText()">Go!</button>
<div id="show" style="display:none;"></div>
<script>
function showText(){
var value = document.getElementById('options').value;
document.getElementById('show').innerHTML = "you chose " + value;
document.getElementById('show').style.display = "block";
}
</script>
</body>
</html>"""
return HttpResponse(myPage)
This is my code right now. It runs on a local server using Django, and all it does is show a dropdown menu, and when I select an option a block shows up that says "you chose this option". What I want is that when I choose a dropdown option and hit the button, it will return the dataframe I created at the very start. I think this may have to be done using ajax and jquery, but I don't really know anything about that. I've been trying to read up on it but I have no idea how I would implement something that ties together my python and javascript.
Django operates server-side, so any computation you'd like to do with Django (or Python) must be done on the server. The server then passes messages (requests and responses) back and forth to the client (ie. a browser). If you want to return some sort of data to Django, you'll have to use a form to submit the information via POST (a request), or you'll need to use Ajax,JQuery. If Django receives a POST request from the client, it can access data at request.POST['myinteger'] for example, and can perform some computation with that integer, then return another HTTPResponse.
Remember, Django is only able to see and interact with things present on the server. Once sent across the Internet, it has no control. That is where Ajax/JQuery, etc. kick in. They can manipulate data on the client side (the browser downloads JQuery when it loads the page). To send data back and forth, you need to rely on sending requests and responses. This is accurate even when using a RESTful API.
I hope this explanation helps a bit.