如何在Ajax请求后访问$ _SESSION变量?

I have a page where people can login and their login request is sent with jQuery's $.ajax to a processing page. On that page all of the errors collected during the login attempt are stored in $_SESSION['error'].

How can I access this variable to alert users of the errors after the attempt is made. I know how to access a session variale, I mean how do I access a php variable without reloading the page. The only way I currently am aware of is to inject them on page load, but there must be some way to access them with JavaScript after they have changed due to an Ajax request.

Unfortunately you cannot directly access the PHP $_SESSION[] array from JavaScript. This is by design, because one of the major points of using a Session, is that the data is saved on the server side, unmodifiable by the end user, and therefore your Javascript.

What you could do however, is include the error list in your ajax response. Chances are you are doing an ajax request that returns a 'json' type format. Just include your error list in your json returned, and use the JavaScript to display them. I recommend not sharing the entire $_SESSION array, since it could give away some key information about the interworkings of your PHP.

Also, if you are not currently doing an ajax request that expects json, back, then consider switching it up so that you are expecting and returning json. You can provide much more hidden data this way, instead of just some HTML or text.

Hope this helps