I am currently building a website, which until quite recently was purely PHP. However I am now making trying to have the site use more AJAX, to lessen the page reloads. In PHP I had a lovely object orientated user class with methods for updating data, logging out, and so on. When a user logs on this would be stored as a session variable, and then any page that wishes to do anything the user could just grab it from the session and call it's methods. Clearly this use of php objects and the session doesn't really work with ajax. However I don't want to have to scrap storing the user in an object (which neatens things up somewhat), so don't just want to go down the route of defining a ton of js functions that grab the current username, and use the to do mysql queries through ajax. Am I being stupid here, and what route would people recommend I take.
- Anybody can ask a question
- Anybody can answer
- The best answers are voted up and rise to the top
AJAX requests send the cookie by default. Assuming that you are mapping your user object to the PHP session, the request over AJAX should automatically have access to the session and the user object.
If you're using another method to handle sessions (e.g. a session id added to the query string) a) be wary of session spoofing, and b) append it to the AJAX request manually. And VOILA.
Sessions and objects still work with ajax. Sessions persist information on the server-side and objects are just organization structures for the code that is executed there. Much of what you are asking is stuff you pick up from experience programming in general. You should do a little reading and planning to come up with a more solid blueprint of how you want the application to work.
First, check out resources like the following:
www [dot] phptherightway [dot] com
These are the fundamentals of code organization. Learn them early and life will be easier down the road. Once you have those down pat, you will likely know where to go to find more advanced solutions. Of course, stackoverflow is a great resource to find all kinds of solutions.
Always keep in mind that with AJAX, you are doing the same request/response cycle you always do from the server-side perspective. From the client side perspective, you are treating sections of the page as independent little browsers that are capable of making new requests while you are looking at the page. So, with that in mind the following example would be a method of achieving what you are looking to do.
header file segment