Ajax C#(cSharp) Javascript PHP 

How to create server side session using javascript

It is possible to create a server-side session using javascript for any server-side programming language like PHP, C#, Python etc. by just calling server side function using ajax calls as shown below.

To do that, first create a server side application file and write the session variables which you want to set, then in client side javascript just pass the data which you need to set as a session to the server side application function using Ajax call as shown in below examples

First, we will take an Example of C#/Asp.net.

Javascript Ajax call

<script>
var obj={
  sessiontoset1:"data1",
  sessiontoset2:"data2"
}
$.ajax({
            type: "POST",
            url: "pagename.aspx/SessionFunctionName",
            data: JSON.stringify(objs),
            contentType: "application/json; charset=utf-8 ",
            dataType: "json",
            success: function (data) {
                    alert("session set");
            }
      });
</script>

C# Code to set the session at server side

[WebMethod]
   public static string SessionFunctionName(string sessiontoset1,string sessiontoset2)
   {
     Session["sessiontoset1"]=sessiontoset1;
     Session["sessiontoset2"]=sessiontoset2;
     //if above session setting doesn't work, set as shown below
    //HttpContext.Current.Session("sessiontoset1")=sessiontoset1;
    //HttpContext.Current.Session("sessiontoset1")=sessiontoset1;
 }

For PHP

javascript for PHP

var obj={
sessiontoset1:"data1",
sessiontoset2:"data2"
}
$.ajax({
type:"POST",
url:"sessionfunction.php", 
data: obj, 
success: function (data) {
 alert("Session Set");
}

});

Create a file called sessionsfunction.php

<?php

if(isset($_POST['sessiontoset1'])){

$_SESSION['sessiontoset1']=$_POST['sessiontoset1'];

$_SESSION['sessiontoset2']=$_POST['sessiontoset2'];

}
    
?>

 

Arjun is is a web developer/designer, who is fond of the web. He lives in Manipal, Karnataka, India.
Also Read:  Google API to Calculate a Distance in PHP / Mysql

Related posts