By using below code on button click I get the href attribute value, until this everything is fine but when I got my href
link on button click we want to store it in the session variable (ie var href
) because we also use this variable elsewhere. Please suggest me how to store JavaScript variable in session.?
<script>
$(document).ready(function(){
$('.button').click(function(){
var href = $(this).val();
alert(href);
})
});
</script>
<button value="<?php echo $value['3']; ?>" class="button" style="background-color:#ff8c21;">Buy Now</button>
You can't set SESSION WITH JAVASCRIPT this is because its server side functionality so if you want to use this data
some where else you can send a ajax request to server and there you can create session for this data.
JS:
$(document).ready(function(){
$('.button').click(function(){
var href = $(this).val();
$.ajax({
type: "POST",
url: url,//url to file
data: {val:href},
success: function(data){
//success
};
});
});
});
PHP:
session_start();
if(isset($_POST['val']))
{
$_SESSION['href'] = $_POST['val'];//created a session named "href"
}
//use session
if(isset($_SESSION['href']))
{
echo $_SESSION['href'];//use your session.
}
Please try it if you want to use session using jquery First include jquery-1.9.1.js and jquery.session.js
$(document).ready(function(){
$('.button').click(function(){
var href = $(this).val();
$.session.set("yoursessioname", "storevalue");
})
});
alert($.session.get("yoursessioname"));
more detail http://phprocks.letsnurture.com/create-session-with-jquery/
If you want to store it in session which is SERVER side then you need use ajax pass variable and store it in php for example with
<?php
session_start();
!isset($_POST['var']) ?: $_SESSION['var'] = $_POST['var'];
but you can think of using cookies as well, then you don't need PHP it can be done only with JavaScript. There is nice Jquery plugin for that
JavaScript works in the browser and PHP sessions are activated on the server, so you can't change session variables without sending a request to the server eg via a url or by submitting a form. BUT you could use sessionStorage, which is a similar principle but lives in the browser and is modifiable by javascript.
eg. (inside javascript)
sessionStorage.myvariable=myVal
etc. It will live as long as your tab is open (from page to page).
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.