I see you put this in the comments.
you are right it seems to work. But on future use I'am calling the
file from different pages. I will store how often the user did his
ajax-call in a database. So that mean I cant do that serverside?
My question for your question is why even bother with the session, just store it in the database the whole time. The reason I post this as an answer is because what happens if they close the browser? before you save it in the database.
Granted you will still want to get the session working. Because on the server side you may want to pull their user id or other information out of it.
To explain the session issue:
My money is on the domain path ( www. sub-domain -vs- no sub-domain ) that others have mentioned as to why you are having problems with the session cookies. It's not really that you are losing the session. But most likely, if you were to view the cookies stored in your browser for the site you will probably have 2 of them. Which means that you are using one session for the www. sub-domain and one for the site without the domain.
You can always force the www. on your site with some .htaccess rules too.
.htaccess - how to force "www." in a generic way?
Anyway, the specifics below depend on your exact implementation, which is why I'm not posting code.
On the server side.
authenticate use in the session, Or you could do IP address here etc...
Use user id for unique field in database, or user id and some other field(s) like date or url visited.
have a numeric field 'views' or such. And, maybe a field for the url they are visiting?
on each ajax request pull the users record out of the DB, increment the view field and save any other data you want too.
The database queries will be super fast just pulling out one row each with a good numeric index, like a user id etc..
In short I would just skip the whole saving in the session bit, because like I hinted at if they close the browser you lose your count. Besides, how will you know when to save it in the database? There is no way to tell sever side when they disconnect, except for to use a heartbeat like the ajax call. You cant rely on them to log out properly.
I have implemented a similar system, to track time spent doing data entry by some outside contractors we use at my Job.
In that implantation, I use the id of record they are editing, and their user ID as keys, then I have a timestamp for last viewed time, so that when the ajax call hits I pull out the last viewed time ( if its less then a few minutes old ) and in a separate field I keep the total seconds spent working. Then with some basic math I can add the new elapsed seconds into the total and wah-lah, I can keep a fairly accurate track of how long they have the record open for.