Tutorial :can you access $_SESSION[] values in an ajax'd page?



Question:

if on a page i have

echo $_SESSION['user_id'];  

and it echo's 1

can i access that value on a page called using ajax (on the same server & domain) or do i need to pass that value through with the ajax request?


Solution:1

Yes you can access it, the same cookies are, by default, passed with an AJAX request, which is what you need for session (again, by default).


Solution:2

If you look at XHR requests "out of the box", you'll understand that there is generally no difference, in the client or in the server, between a "classic" HTTP request and an XmlHttpRequest.

The only difference is in the client, in two ways: you get the answer without leaving the current page, and you are free to do what you want with that in your javascript.

So in the PHP side of things everything is the same.

One point that might need some attention: if for instance the client does many asynchronous requests that might take some time to process in PHP, you'll want to be careful with the default file-based PHP sessions. An Apache/PHP process that has opened the session will essentially block other requests that also want to access the session. session_write_close() is your friend.


Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »