Create the session during ajax call (php-xajax)

天大地大妈咪最大 提交于 2019-12-13 15:42:29

问题


i need to avoid the creation of the session in the application unless it is completely necessary.

I have noticed that xajax calls dont work properly if the session is not started :(. My first approach was to create the session (if it doesn't exist) at the begining of the xajax function, however, it doesn't work the first time the user invokes the call (it works the second time since the session was created).

There is any way to handle/fix this situation?

Edit: an example code:

function example ($parameters) {
    if (!isset($_COOKIE["PHPSESSID"])) {
        session_start(); // we create the session if it didn't exist previously 
    }
    $response = new XajaxResponse();
    .....
    return $response;
}

My idea is to create the session when the user makes an ajax call. With this situation, the first time i call the "example" function it doesnt work. The second it goes ok, i think because the session was created.

EDIT: Hello, i have noticed a problem under chrome and explorer :(. The first ajax call is not received (i get not answer). Than means the user needs to click twice in order to receive the properly answer (with a popup for example)

Thanks!


回答1:


The issue seems to be the fact that you are not calling session_start() if $_COOKIE['PHPSESSID'] is set, and consequently the session is not initialized for the current ajax request. You must call session_start() on every script that uses the session -- it isn't just for session initialization.

function example ($parameters) {
    // If this function uses the session, you MUST call session_start()
    // Don't do it conditionally.
    session_start(); 

    $response = new XajaxResponse();
    .....
    return $response;
}

If all your ajax handler functions make use of the session, then you might as well just call session_start() at the top of the file that contains them. If you don't want the session loaded prior to ajax calls, then segregate them into their own PHP script, while you do not call session_start() on the main script they initially load.




回答2:


For session you have to reload page without reloading page session can not create..... And Ajax is useful for without reloading the whole page.



来源:https://stackoverflow.com/questions/12800653/create-the-session-during-ajax-call-php-xajax

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!