开发者

Setting a PHP $_SESSION['username'] using a jQuery $.post call and a callback method

I've researched and played around a fair bit, but I am 开发者_如何学Pythonstumped. Essentially I want to setup my site so that it can detect if a user is 'logged in' and thereby change the way it looks: removing the "Sign In" link and replacing it with a "Sign Out" link, and so forth.

For testing purposes I started my index.html page with:

<?php 
session_start(); 
$_SESSION["username"]="javaman";
?>

Next, I call my setup function from within the jquery document.ready:

$(document).ready(function() {
    setup_page();
};

The setup function looks like:

function setup_page()
{
    var username = get_user();

    //check for error
    var index = username.indexOf("error");

    //if not an error
    if(username.length > 0 && index == -1)
    {
        //do the jquery calls to hide/show links
    }
}

And that get_user function looks like:

function get_user()
{
    var result;

    $.post("./session.php", {action : "get", key : "username", value : "val"}, function(data){
            result = data;

        });

    return result;
}

The session.php is a simple app that takes in 3 post values and hopefully spits out the proper result, the problem I am running into is that the js result variable is often undefined, especially so when I debug via the IE dev toolbar. FF seems ok though. Am I using the callback in the correct way? I've tried putting alert() functions everywhere to figure out where the code is screwing up, but that doesn't help either as often the alert's say the result is undefined. Meanwhile, it seems like the get_user calls the post function but the stack immediately returns and never gets to the return statement until AFTER the get_user has returned a value of.. undefined. I believe I am misunderstanding the code flow here. I am used to C where logically one function follows another. In that vein I am interpreting the callback to essentially be like:

int i = callback_function(post("some data"));

So in my mind the post completes it's action and then calls another function or at least performs another action and then that completes and then the get_user can return it's value.

Or is the order of operation: post, get_user, callback?

...confused in Seattle


Internet Explorer does not natively support indexOf on arrays. Use jQuery's $.inArray() instead:

var index = $.inArray("error", username);


Keep in mind that AJAX stands for Asynchronous Javascript and XML. So the callback fires as soon as a response comes, but the rest of execution goes on. If you want to lock the execution until AJAX-request will be completed, use

$.ajaxSetup({async:false});

before AJAX call.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜