Take the 2-minute tour ×
Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. It's 100% free, no registration required.

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.

share

2 Answers 2

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.

share
    
How can I modify the user object from JS though as it is a php object? I'm guessing I'll have to echo it out from the server using json_encode. –  handuel Mar 25 '13 at 21:29
    
Do you have to expose it to the front end? –  Mike Brown Mar 26 '13 at 15:54

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

www [dot] codecademy [dot] com/tracks/javascript-combined

More specifically:

http://www.phptherightway.com/pages/Design-Patterns.html https://en.wikipedia.org/wiki/Front_Controller_pattern

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

<script>
    jQuery(function(){
        jQuery('#login').click(function(e){
            //stops form from submitting via normal behavior
            e.preventDefault();
            //cache the form element because each time
            //you do a jQuery() search, a puppy dies
            var form = jQuery(this).parents('form');
            jQuery.post(
                form.attr('action'),
                form.serialize(),
                function(data) {
                   var responseString = 'Logged in as ' + data.firstName + ' ' + data.lastName;
                   form.html(responseString);
                }
            );
        });
    });
</script>
<form action="ajax_controller.php">
    <input type="hidden" name="action" value="authenticate" />
    <input type="text" name="username" />
    <input type="password" name="password" />
    <input type="submit" />
</form>

ajax controller

<?php
    if ($_SERVER['HTTP_X_REQUESTED_WITH']) {
        /* Safety first, but use the mysqli version of 
         * this if you are using a mysql db
         */
        foreach ($_POST as $post)
            $_POST = mysql_real_escape_string($post);

        if ($_POST['action'] === 'authenticate') {
            $user = new User($_POST['username']);
            $success = $user->authenticate($_POST['password']);

            //let's pretend authenticate() returns true or error message
            if ($success === true) {
                $response = array(
                    'firstName' => $user->get_firstName(), 
                    'lastname' => $user->get_lastName()
                );
                return json_encode($reponse);
            } else {
                return $success;
            }
        }
    } else {
        //bark and throw exception, or return html, or whatever
    }
share

This site is currently not accepting new answers.

Not the answer you're looking for? Browse other questions tagged .