简体   繁体   中英

Set session var with ajax

I want to create a session var . I have a web page with some tabs that don't recharge when I active one another. So, I don't know how to set my session var.

Indeed, my first tab will generate the session var when the user submit the form into this tab. I'm trying to do it with ajax. So in my ajax file, I have this to set my var :

if(pg_num_rows($res) == 1)
 {                                  
    $flag=false;
    $message = "L'identifiant de l'essai existe déjà dans la base";
    array_push($tab_erreur,$cpt,$message);
  }else {
    $sessionIDEssai=$ligne[1]; //Here is my session var
  }  

After, I want to return that value with an other like this :

echo json_encode($tab_erreur),$sessionIDEssai;

First of all I don't know if it's correct, because I can't get it in my callback function.

 function insert_essai_callback(responseObject,ioArgs) .
 {
    var jsonobject = eval(responseObject);
    console.log(jsonobject);
 }

I can get the first var $tab_erreur .

And after I don't know how to set my session var for all my tabs. I think that at the return of the ajax, I will get the value and I could set it and use it, but I'm not sure.

EDIT

I send an array in my ajax request like that :

$(document).ready(function(){
        $('#submit_button_essai').click(function(){

            $.post("ajax_insert_essai.php",{arr:data_essai}, insert_essai_callback,'json'); 
        });
    });

Ajax

 $.ajax({
        type : 'POST',
        url : './session.php',
        dataType: "json",
        data: data,
        success : function(data){},
        error : function(){}
 });

PHP

<?php
    session_start();
    $_SESSION['data']=$_POST['data'];
    echo $_SESSION['data'];
    ?> 
});

Data is what you send through a POST, now echo can return that data or a different amount of data to your Ajax request as a response.

Using, $.post():

$.post({
    url: url,
    data: data,
    success: success,
    dataType: dataType
});

However, $.ajax(), is much much better, since you have more control over the flow, and if success do this etc.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM