How to access php session in javascript file?

Issue

Below is my code:

index.php file

javascript of index.php file

function Result()
{
  var marks = 55;
  document.getElementById("hdnmarks").innerHTML= marks; 
  window.location = "results.php";
}

HTML of index.php

<input type="hidden" name="hdnmarks" id="hdnmarks">

Description: I have a web page with url localhost/index.php. In index.php, I have a submit button on the click of which I call Result javascript method which sets the marks = 55 and put it into the hidden field and takes me to the results.php page.

In results.php, I have to insert value of marks in the database. But how should I access the marks as those were stored in the hidden field of index.php file?

I want to put marks in the session, but how should I maintain the PHP session in javascript function? I mean where and when should I put marks in the session before moving to results.php?

Solution

you can start session on your page like <?php session_start();?> and create hidden field for session like this

<input type="hidden" name="mysession" id="mysession">

and modify javascript function some thing like this

function Result(){
  var marks = 55;
  document.getElementById("mysession").innerHTML= <?php echo session_id();?>; 
  document.getElementById("hdnmarks").innerHTML= marks; 
  document.getElementById('Form').submit();
}

change the Form name with your form name

Answered By – Ram Sharma

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published