Dikobraz
Dikobraz

Reputation: 659

jquery and php ajax sessions

Here is what I do:

my login form is on www.mysite.com/login.html: (subdomain www!)

 function authenticate(userName, password) {
    $.ajax
    ({
        type: "POST",
        //the url where you want to sent the userName and password to
        url: 'http://server.mysite.com/ajax/auth.php',
        dataType: 'json',
        async: false,
        cache: false,
        data: 'vardas='+userName+'&psw='+password,
        success: function (data) {
                {
                    window.location.replace('/main.html');
                }
        }
    })
    }

Here is my ajax/auth.php:

header('Content-type: application/json');
header ("Access-Control-Allow-Origin: http://www.mysite.com");
header('Expires: ' . gmdate('r', 0));

session_start();
$_SESSION["ok"] = 1111; <- test value

Here is main.php:

<script>
  $(function() {
    $('#home').load('http://server.mysite.com/ajax/loader.php', function() {
    })
  });
</script>
<div id=home></div>

Here is my ajax/loader.php :)

<?
    header ("Access-Control-Allow-Origin: http://www.mysite.com");
    header('Expires: ' . gmdate('r', 0));

    session_start();

    var_dump ($_SESSION); <---- OUTPUT IS (0) EMPTY!! Why ?
?>

Why this does'nt work? I always get $_SESSION empty.

Upvotes: 4

Views: 2280

Answers (4)

webcoder
webcoder

Reputation: 1375

If all domains are on same server, use these three lines everywhere before call to session_start

$session_name = session_name("somename");
ini_set('session.cookie_domain', '.mysite.com');
ini_set('session.save_path', 'C:\tmp');
session_start();

Upvotes: 2

Aldee
Aldee

Reputation: 4518

I don't understand why you have a login.html and there after the ajax execution, you have this main.php redirection page? Am I right? If this is the case, why won't you just simply redirect the user after form submission and let the server validates the authentication before it renders the page?

Now, if that is not the case, always be reminded that session data will not take effect when you set it by ajax and in your current page, you will call it. It definitely will not work.

Upvotes: 0

Liam Bailey
Liam Bailey

Reputation: 5905

You are never calling the authenticate that runs the ajax request, to call auth.php and sets the session vars. you .load http://server.mysite.com/ajax/loader.php that calls session_start, but at no point do you call authenticate() so your session never gets filled.

Also, Access-Control-Allow-Origin isn't fully supported yet, so depending on the browser it may be blocking your cross-domain request.

Upvotes: 0

Jonathan M
Jonathan M

Reputation: 17441

session_start(); MUST be the very first thing to produce any output. You have it below your header() stuff. It needs to go first.

See the first note here: http://www.php.net/manual/en/function.session-start.php

Upvotes: 2

Related Questions