Converting a user management system to use ajax

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.

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.

2

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
    }

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật