I want to take the session data in .js file.Here i want the data in a function Now i'm directly put the value.How to take it from session.
.js file
function callAllfnt(){
get_data(1) ;
}
I want the 1 as session data.How to take it
I want to take the session data in .js file.Here i want the data in a function Now i'm directly put the value.How to take it from session.
.js file
function callAllfnt(){
get_data(1) ;
}
I want the 1 as session data.How to take it
Share Improve this question asked Feb 4, 2016 at 10:37 robinsrobins 1,6687 gold badges34 silver badges71 bronze badges 1-
PHP tag is not allowed in
.js
file. You have to useajax
for it. – Mr. Engineer Commented Feb 4, 2016 at 10:40
4 Answers
Reset to default 3If you want it on page load the try this:
function callAllfnt() {
var data = "<?php echo $_SESSION['givenName']; ?>";
}
In later part in the life cycle of the application, use AJAX
1)
View File
<script type="text/javascript">
var Sessionvalue = "<?php echo $this->session->userdata('session_name')";
<script>
After load your js file
<script src="<?php echo base_url(); ?>js/file.js" type="text/javascript"></script>
JS FILE
function callAllfnt() {
var data = SessionValue;
}
(OR)
2) Using Ajax call and Get the Session value
You need to create php script that will return Session data and call that with ajax like this:
php
if (isset($_GET['var'])) {
echo json_encode($_SESSION[$_GET['var']]);
}
js with jQuery:
function get_data(variable, callback) {
$.get('session.php', {'var':variable}, function(data) {
callback(data);
}, 'json');
}
and you can call that function using:
get_data(1, function(value) {
alert(value);
});
just use php tag with in single quotes if you java script is written in html page like
function callAllfnt() {
var value = '<?php echo $_SESSION["varName"]; ?>';
get_data(value) ;
}
But if your javascript code is written seperate js file then use ajax.
Third option is if your javascript file included in php file then create a javascript variable on top of js file including code and use that variable in js file.