开发者

Create a session before an ajax call

I have this website where I can interact with the web both as a logged or anonymus user. When I click a link I call an ajax function:

you click here:

<a id="alcrearuta" class="'.$row->urlamigable.'" href="#">añadir a ruta</a>

This is my ajax function:

var valor=$("#alcrearuta").attr('class');
$("#alcrearuta").click(function(){
    $.ajax({
        type: "GET",
        url: "../ajax/ruta.php",
        data: "urlamigable=" + valor,
        dataType: 'html',
        success: function(data) {
            $("#listaruta").html(data);
        }
    });        
});

The thing is I have two possibilities: either a logged user clicks the link and the ruta.php does its stuff on the database considering the userid that's set in the session or I have an anonymous user that wants to do something similar.

In my ruta.php I have:

if(!empty($_SESSION['Username'])){
    //Insert stuff on DB
}else{
    //I wish I could create the session here but I can't since it's an ajax call
}

What I need is at some point between the click in the link and the end of the ajax function I can set my $SESSION['Username'] variable to get a new value (since the user it's not logged 开发者_如何学运维in, it's currently empty and thus my inserts on the database not working)


if you want to use sessions in php, your php script (ruta.php) schould start with

session_start();

from that point you can assign any variable to $_SESSION['Username']

$_SESSION['Username'] = something_to_generate_a_Username;

Just like any other server request.


You could use jquery cookie library to create a session cookie.

$.cookie("Username", "NOTLOGGEDINUSER");

https://github.com/carhartl/jquery-cookie

http://www.electrictoolbox.com/jquery-cookies/

and in beforeSend for Ajax, you can check if username cookie exists, other wise, create the cookie with "NOTLOGGEDINUSER"


Maybe on the click do another AJAX call just to set the SESSION?

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜