Skip to content
Advertisement

How to access php session in javascript file?

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?

Advertisement

Answer

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

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement