Vlad
Vlad

Reputation: 1797

Using PHP sessions in jQuery/HTML/Ajax

After a successful login attempt my php script starts a session like this:

    session_set_cookie_params(1800,'/','www.mydomain.com',true);
    session_start();
    header("location:mainpage.html");

Now my questions are:

mysession.php:

     <?php
     session_set_cookie_params(1800,'/','www.mydomain.com',true);
     session_start();
     ?>

somewhere in mainpage.html:

    function getHttpRequestObj()
    {
        if (window.XMLHttpRequest)
        {// code for IE7+, Firefox, Chrome, Opera, Safari
            return new XMLHttpRequest();
        }
        else
        {// code for IE6, IE5
            return new ActiveXObject("Microsoft.XMLHTTP");
        }
    }

    function callSession(id)
    {
    var xmlhttp = getHttpRequestObj();
    xmlhttp.onreadystatechange=function()
      {
      if (xmlhttp.readyState==4 && xmlhttp.status==200)
        {
        document.getElementById(id).innerHTML=xmlhttp.responseText;
        }
      }
    xmlhttp.open("GET","mysession.php",true);
    xmlhttp.send();
    }

And then in the outmost div (name='main') in mainpage.html

      $(document).ready(function() {
callSession('main');
});

Upvotes: 0

Views: 1276

Answers (1)

Vlad
Vlad

Reputation: 1797

Problem solved by adding the following code at the top of my mainpage.html and renaming it to mainpage.php

<?php
session_start();
$id = $_SESSION['id'];
?>

Now I can access my userid from anywhere by doing

<? echo $id ?>

Upvotes: 2

Related Questions