Im trying to set a session variable using AJAX but it doesnt seem to work:

This is my PHTML page:

<?php
session_start();
?>

//SOME CODE


            <script type="text/javascript">



                $j(document).ready(function() 
                {
                    var variablecalle=$j("#listadetiendas").val();



                    var data = 'calle='+variablecalle;
                    $j.ajax({
                            url: '../../updatesession.php',
                            type: 'POST',
                            data: data
                            })    

                });

Then this is my "updatesession.php" page:

<?php
    session_start();
    $_SESSION['calle']=$_POST['calle'];
?>

Hi riahc,
Basing from your ajax URL(using cookies for session id storage),one way for it not to be updated is wrong session ID, or with a browser with a setting of not saving cookies; also assuming you referenced jQuery to $j variable. So let's start first with encoding your data, and checking if you have the same session id, and there's no inconsistency or regeneration of session id ongoing.

<?php
session_start();
?>

//SOME CODE


            <script type="text/javascript">



                $j(document).ready(function() 
                {
                    var variablecalle=$j("#listadetiendas").val();

                    //save the current session id in your ajax page.
                    var currentSessionID = <?php session_id(); ?>;

                    var data = encodeURIComponent('calle='+variablecalle);
                    $j.ajax({
                            url: '../../updatesession.php',
                            type: 'POST',
                            data: data
                            }).done(function(data){
                                var retData = JSON.parse(data);
                                if(retData.sessID != currentSessionID){
                                    alert("doesn't have an equal session id. \n current: " + currentSessionID + "\nIDinAjaxPage: " + retData.sessID);
                                }
                                if(!retData.calleSet){
                                    alert("calle was not set. due to wrongid");
                                }
                                alert("sent calle: " + encodeURIComponent('calle='+variablecalle)+ "\nRecieved calle: " + retData.callePostVal);
                            }); 

                });

your php script should look like this:

<?php
    session_start();
    //echo if the calle session do exists
    echo '{' . '"calleSet":' . (isset($_SESSION['calle'])?'true,':'false,')
    //echo the sessID
        . '"sessID":' . '"'. session_id() .'",'
    //resend the post value of calle
        . '"callePostVal":" . '"'. $_POST['calle'] .'"}';
?>

if the recieved an alert button with a message "doesn't have an equal se..." then, there was a problem witht the session id. It will also echo the current and the ajax response session id. if you recieved "calle was no..." , then there might be a problem retrieving the "calle" in session, this will conclude our assumption if subsequently pops up after the first one.
Also, this will always pop up the sent data info.

Please take note, these popup will only run from a successful ajax call. Let me know if you need clarifications.

Something is wrong with the PHP code so I put:

<?php



    session_start();
    echo ("post of calle ". $_POST['calle'] );
    echo ("session id is ". session_id());

?>

New code:

$j(document).ready(function() 
                {
                    var variablecalle=$j("#listadetiendas").val();

                    var currentSessionID = "<?php echo session_id(); ?>";
                    var data = encodeURIComponent('calle='+variablecalle);


                    //var data = 'calle='+variablecalle;
                    /*$j.ajax({
                            url: '../../updatesession.php',
                            type: 'POST',
                            data: data
                            }) */

                            $j.ajax({
                            url: '../../updatesession.php',
                            type: 'POST',
                            data: data
                            }).done(function(data){
                                var retData = JSON.parse(data);
                                if(retData.sessID != currentSessionID){
                                alert("doesn't have an equal session id. \n current: " + currentSessionID + "\nIDinAjaxPage: " + retData.sessID);
                                }
                                if(!retData.calleSet){
                                alert("calle was not set. due to wrongid");
                                }
                                alert("sent calle: " + encodeURIComponent('calle='+variablecalle)+ "\nRecieved calle: " + retData.callePostVal);
                                });    
                });

PHP:

<?php
    session_start();
    echo ("post of calle ". $_POST['calle'] );
    echo ("session id is ". session_id());

?>

Firebug says:

SyntaxError: JSON.parse: unexpected end of data

var retData = JSON.parse(data);

You're right, there were. Here's the updated php script:

<?php
    session_start();
    //echo if the calle session do exists
    echo '{' . '"calleSet":' . (isset($_SESSION['calle'])?'true,':'false,')
    //echo the sessID
        . '"sessID":' . '"'. session_id() .'",'
    //resend the post value of calle
        . '"callePostVal":' . '"'. (isset($_POST['calle'])?$_POST['calle']:'') .'"}';

Please let me know the result, afterwards.

In reference to Firebug's message:

SyntaxError: JSON.parse: unexpected end of data

var retData = JSON.parse(data);

It's due to a malformed json data sent by :

<?php
    session_start();
    echo ("post of calle ". $_POST['calle'] );
    echo ("session id is ". session_id());

?>

The recently updated script i posted will fix it. Anyway, here it is too.

<?php
    session_start();
    //echo if the calle session do exists
    echo '{' . '"calleSet":' . (isset($_SESSION['calle'])?'true,':'false,')
    //echo the sessID
        . '"sessID":' . '"'. session_id() .'",'
    //resend the post value of calle
        . '"callePostVal":' . '"'. (isset($_POST['calle'])?$_POST['calle']:'') .'"}';

Same errror.

Here is the code again:

 $j(document).ready(function() 
                {
                    var variablecalle=$j("#listadetiendas").val();

                    var currentSessionID = "<?php echo session_id(); ?>";
                    var data = encodeURIComponent('calle='+variablecalle);


                    //var data = 'calle='+variablecalle;
                    /*$j.ajax({
                            url: '../../updatesession.php',
                            type: 'POST',
                            data: data
                            }) */

                            $j.ajax({
                            url: '../../updatesession.php',
                            type: 'POST',
                            data: data
                            }).done(function(data){
                                var retData = JSON.parse(data);
                                if(retData.sessID != currentSessionID){
                                alert("doesn't have an equal session id. \n current: " + currentSessionID + "\nIDinAjaxPage: " + retData.sessID);
                                }
                                if(!retData.calleSet){
                                alert("calle was not set. due to wrongid");
                                }
                                alert("sent calle: " + encodeURIComponent('calle='+variablecalle)+ "\nRecieved calle: " + retData.callePostVal);
                                });    
                });

PHP

<?php

    session_start();
    //echo if the calle session do exists
    echo '{' . '"calleSet":' . (isset($_SESSION['calle'])?'true,':'false,')
    //echo the sessID
        . '"sessID":' . '"'. session_id() .'",'
    //resend the post value of calle
        . '"callePostVal":' . '"'. (isset($_POST['calle'])?$_POST['calle']:'') .'"}';


?>

Instead of building the JSON response with echo and string concatenation, I suggest building an array and using json_encode() on it.

I put a alert(data); before

var retData = JSON.parse(data);

And it returns nothing. Empty.

Also did a alert of variablecalle and it has a value.

Instead of building the JSON response with echo and string concatenation, I suggest building an array and using json_encode() on it.

What is the best/correct way to do this?

Hi Riahc:
instead of var retData = JSON.parse(data);, use var retData = $j.parseJSON(data);

if nothing goes well, then just ouput the data in your body. like this:

//...some codes
                            type: 'POST',
                            data: data
                            }).done(function(data){
                                $j(document.body).append("currSessID: "+currentSessionID+" " +data);    
                });

Assess the result from there.

Change that and now it gives me:

TypeError: retData is null

if(retData.sessID != currentSessionID)

New code:

 $j(document).ready(function() 
                {
                    var variablecalle=$j("#listadetiendas").val();

                    var currentSessionID = "<?php echo session_id(); ?>";
                    var data = encodeURIComponent('calle='+variablecalle);


                    //var data = 'calle='+variablecalle;
                    /*$j.ajax({
                            url: '../../updatesession.php',
                            type: 'POST',
                            data: data
                            }) */

                            $j.ajax({
                            url: '../../updatesession.php',
                            type: 'POST',
                            data: data
                            }).done(function(data){
                                $j(document.body).append("currSessID: |"+currentSessionID+"| data |"+data+"|");   
                                var retData = $j.parseJSON(data);
                                if(retData.sessID != currentSessionID){
                                alert("doesn't have an equal session id. \n current: " + currentSessionID + "\nIDinAjaxPage: " + retData.sessID);
                                }
                                if(!retData.calleSet){
                                alert("calle was not set. due to wrongid");
                                }
                                alert("sent calle: " + encodeURIComponent('calle='+variablecalle)+ "\nRecieved calle: " + retData.callePostVal);
                                });    
                });

Result:

currSessID: |3j5ncc0m9uggb34bisjdmogr96| data ||

Priteas was right it's better to build a json from json_encode, here it is, based from priteas' suggestion.

<?php
    session_start();
    $f = new StdClass();
    $f->calleSet= isset($_SESSION['calle'])?true:false;
    $f->sessID = session_id();
    $f->callePostVal = isset($_POST['calle'])?$_POST['calle']:'';
    echo json_encode($f);

Anyhow, moving forward, i'm quite surprised there were no data being recieved from the data variable.

Anyway, will create a simple script that you can follow.

Hi riahc,
let me know if you have any clairifcation when it comes to the code below.
currently i can't understand how come there were no recieved data from your ajax code. I was thinking it might be a version problem, or someting.

test.php
<?php
session_start();
$f = new StdClass();
$f->myInputSessSet= isset($_SESSION['myInput'])?true:false;
$f->sessID = session_id();
$f->myInputPostVal = isset($_POST['myInput'])?$_POST['myInput']:'';

echo json_encode($f);
sample.php
<!DOCUMENT HTML>
<html>
    <head>
        <script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
        <script type="text/javascript">
            $(document).ready(function(){
                //on any changes in the myInput value, send an ajax call
                // then append the data in the currSess div
                $("#myInput").on({
                    "change": function(evt){
                            //encode the value of myInput to be more
                            // friendly
                            var inputdata = 'myInput='+encodeURIComponent(evt.target.value);
                            //send the input thru post
                            $.ajax({
                                url: "test.php",
                                type: "POST",
                                data: inputdata
                            }).done(function(data){
                                    //append the recieved data on success
                                    $("#currSess").html(data);
                            });
                        }
                    });

                //in the event that a user keyed enter
                //submit the input data
                $("#myForm").submit(function(){
                    $.ajax({
                        url: "test.php",
                        type: "POST",
                        //serialize the form input data
                        // just like how we encode the value
                        // of myInput
                        data: $(this).serialize()
                    }).done(function(data){
                            //append the recieved data on success
                            $("#currSess").html(data);
                    });

                    // Make sure it doen't submit and use the defalt
                    // behavior
                    return false;
                });
            });
        </script>
    </head>
    <body>
        <form id="myForm">
            <h3>Send the data on a change event</h3>
            <input type="text" id="myInput" name="myInput" value="jjj" />
            <input type="submit" />
            <h3>The data recieved from an AJAX call</h3>
            <div id="currSess"></div>
        </form>
    </body>
</html>

Thank you pritaeas and gon1387.

gon1387, Im going to adapt the code you posted to what I have....

Might take a minute or two.

Still nothing. Odd.

PHTML:

                    start
                    <div id="currSess"></div>
                    finish
            <script type="text/javascript">



                $j(document).ready(function() 
                {
                    var variablecalle=$j("#listadetiendas").val();

                    //var currentSessionID = "<?php echo session_id(); ?>";
                    var data='calle='+encodeURIComponent(variablecalle);
                    //var data = encodeURIComponent('calle='+variablecalle); <---------big difference between this and line before it


                    //var data = 'calle='+variablecalle;
                    $j.ajax({
                            url: '../../updatesession.php',
                            type: 'POST',
                            data: data
                            }).done(function(data){
                            //append the recieved data on success
                            $j("#currSess").html(data);
                            });
                });
                </script>

PHP:

<?php
    /*session_start();
    $_SESSION['calle']=$_POST['calle'];
    $_SESSION['fecha']=$_POST['fecha'];*/


    /*session_start();
    //echo if the calle session do exists
    echo '{' . '"calleSet":' . (isset($_SESSION['calle'])?'true,':'false,')
    //echo the sessID
        . '"sessID":' . '"'. session_id() .'",'
    //resend the post value of calle
        . '"callePostVal":' . '"'. (isset($_POST['calle'])?$_POST['calle']:'') .'"}';*/


    session_start();
    $f = new StdClass();
    $f->calleSet= isset($_SESSION['calle'])?true:false;
    $f->sessID = session_id();
    $f->callePostVal = isset($_POST['calle'])?$_POST['calle']:'';
    echo json_encode($f);


?>

Im kinda of confused now :S

Hi Riahc,

//this was the right one
var data='calle='+encodeURIComponent(variablecalle);

Please update the session var.

session_start();

$_SESSION['calle'] = $_POST['calle'];

$f = new StdClass();
$f->calleSet= isset($_SESSION['calle'])?true:false;
$f->sessID = session_id();
$f->callePostVal = isset($_POST['calle'])?$_POST['calle']:'';
echo json_encode($f);

I would also like to know if the script I made above, without any adaptation with yours, worked for you and you saw the changes.

By the way, here's my understandin with your initial script, let me know if I understood it correctly:

<?php
session_start();
?>

//SOME CODE


            <script type="text/javascript">


                // You inititated to run the code inside once the page
                //  completely loads
                $j(document).ready(function() 
                {
                    // Gets the initial value of "#listadetiendas"
                    //  since this code's ran on page load complete
                    var variablecalle=$j("#listadetiendas").val();


                    // Prepare the data to be sent, use the data of
                    //  "#listadetiendas" 
                    var data = 'calle='+variablecalle;

                    // make an ajax call at the after the page loads
                    //  completely and send the prepared data
                    // Send the data to updatesession.php which is located
                    //  two levels down the path. So if I have this file as
                    //  http://localhost/folder/folder/index.php
                    //  the exact location of updatesession.php is
                    //  http://localhost/updatesession.php and it exists
                    //  in the document folder
                    $j.ajax({
                            url: '../../updatesession.php',
                            type: 'POST',
                            data: data
                            })    

                });

Here;s the php file:

<?php
    session_start();
    //store/update the sent post data to session
    $_SESSION['calle']=$_POST['calle'];

How were you able to know the value of $_SESSION['calle']? Do you have another php file to verify it's existence and value? like

<?php
//file: anotherFile.php
//refresh to check the current value of calle

session_start();
echo isset($_SESSION['calle'])?$_SESSION['calle']:"nothing in $_SESSION['calle']";

(insert 10000000000 curse words here)

I was editing the wrong updatesession.php Damn it. Sorry for wasting your time, guys.

Lets start from the top basically and Ill tell you what I current got. Once again, I apoligize.

PHTML:

start
                    <div id="currSess"></div>
                    finish
            <script type="text/javascript">



                $j(document).ready(function() 
                {
                    var variablecalle=$j("#listadetiendas").val();

                    //var currentSessionID = "<?php echo session_id(); ?>";
                    var data='calle='+encodeURIComponent(variablecalle);
                    //var data = encodeURIComponent('calle='+variablecalle); <---------big difference between this and line before it


                    //var data = 'calle='+variablecalle;
                    $j.ajax({
                            url: '../../updatesession.php',
                            type: 'POST',
                            data: data
                            }).done(function(data){
                            //append the recieved data on success
                            $j("#currSess").html(data);
                            });
                });
                </script>

PHP:

<?php
    /*session_start();
    $_SESSION['calle']=$_POST['calle'];
    $_SESSION['fecha']=$_POST['fecha'];*/


    /*session_start();
    //echo if the calle session do exists
    echo '{' . '"calleSet":' . (isset($_SESSION['calle'])?'true,':'false,')
    //echo the sessID
        . '"sessID":' . '"'. session_id() .'",'
    //resend the post value of calle
        . '"callePostVal":' . '"'. (isset($_POST['calle'])?$_POST['calle']:'') .'"}';*/


    session_start();
    $_SESSION['calle'] = $_POST['calle'];
    $f = new StdClass();
    $f->calleSet= isset($_SESSION['calle'])?true:false;
    $f->sessID = session_id();
    $f->callePostVal = isset($_POST['calle'])?$_POST['calle']:'';
    echo json_encode($f);


?>

This (in the div) gives the following result:

{"calleSet":true,"sessID":"gslqmj45ih6e6cdtg5koc8bol1","callePostVal":"Calle Pruebas"}

What I am intrested in is that "Calle Pruebas". There you have the session ID.

I think it works now....Thats what is looks like.

I think it has something to do with the session id you guys commented:

Put this code:

<?php echo session_id(); ?>

                    start
                    <div id="currSess"></div>
                    finish

                    /*JAVASCRIPT THAT DOES AJAX CALL BELOW*/

And it gave me this (This is the HTML source):

 ncjli2vcfqos4qne8soosi3h63 start
<div id="currSess">{"calleSet":true,"sessID":"gslqmj45ih6e6cdtg5koc8bol1","callePostVal":"Calle Pruebas"}</div>
finish

Where do I continue from here?

If the session id never changed, then you currently have no problem. Basically, it will flow the way you wanted it to be, unless there's an issue with the program's logic.

Well it seems the session id in the PHTML page is different than the one in the PHP page; How can I make (aka force) them use the same session ID?

Set session.use_cookies to true in your ini file.

If it's set to true then, there might be a part of your code which is regenerating the ID. Or you can pass the same id thru URL or echoing it on a page, whatever suits your taste.

I did this:

PHTML:

<?php echo session_id(); ?>

                    start
                    <div id="currSess"></div>
                    finish
            <script type="text/javascript">



                $j(document).ready(function() 
                {
                    var variablecalle=$j("#listadetiendas").val();

                    var currentSessionID = "<?php echo session_id(); ?>";
                    var data='calle='+encodeURIComponent(variablecalle)+'&ses='+currentSessionID;
                    //var data = encodeURIComponent('calle='+variablecalle); <---------big difference between this and line before it


                    //var data = 'calle='+variablecalle;
                    $j.ajax({
                            url: '../../updatesession.php',
                            type: 'POST',
                            data: data
                            }).done(function(data){
                            //append the recieved data on success
                            $j("#currSess").html(data);
                            });
                });

Then in the PHP:

<?php
    /*session_start();
    $_SESSION['calle']=$_POST['calle'];
    $_SESSION['fecha']=$_POST['fecha'];*/


    /*session_start();
    //echo if the calle session do exists
    echo '{' . '"calleSet":' . (isset($_SESSION['calle'])?'true,':'false,')
    //echo the sessID
        . '"sessID":' . '"'. session_id() .'",'
    //resend the post value of calle
        . '"callePostVal":' . '"'. (isset($_POST['calle'])?$_POST['calle']:'') .'"}';*/


    session_id($_POST['ses']);
    session_start();
    $_SESSION['calle'] = $_POST['calle'];
    $f = new StdClass();
    $f->calleSet= isset($_SESSION['calle'])?true:false;
    $f->sessID = session_id();
    $f->callePostVal = isset($_POST['calle'])?$_POST['calle']:'';
    echo json_encode($f);


?>

And it works giving me the result of:

le9vare5h0jgvl49gdmueiffv4 empiezo
{"calleSet":true,"sessID":"le9vare5h0jgvl49gdmueiffv4","callePostVal":"Calle Pruebas"}
termino 

thats all fine but then in ANOTHER php page, I BELIEVE the id is again different because it doesnt work.

I tried doing this with cookies but I believe it gave me similar problems (some domain/path issue I believe it was). Also, HTML5's local storage gave me the same problems. I thought session variables were the way to go :(

Ill keep trying with this session variable.

session.use_cookies is already to true.

Im thinking of ways to do what I want to do...

Got a great idea! :) The problem is I dont know how to write it correctly.

This is pure PHP:

<?php Mage::getSingleton('core/session')->setTest('my test'); ?>

How can I do this:

<script type="text/javascript">



                $j(document).ready(function() 
                {




                    var variablecalle=$j("#listadetiendas").val();

                    <?php Mage::getSingleton('core/session')->setTest( ?>variablecalle <?php); ?>


                });
                </script>

It is EXACTLY what I need. I just dont know how to set it correctly. I can do something like

var currentSessionID = "<?php echo session_id(); ?>";

So I KNOW it works.

OK I got a idea and no error :)

<?php Mage::getSingleton('core/session')->setTest('?><div id="currSess"></div><?php '); ?>


            <script type="text/javascript">



                $j(document).ready(function() 
                {




                    var variablecalle=$j("#listadetiendas").val();



                    var currentSessionID = "<?php echo session_id(); ?>";
                    var data='calle='+encodeURIComponent(variablecalle)+'&ses='+currentSessionID;
                    //var data = encodeURIComponent('calle='+variablecalle); <---------big difference between this and line before it


                    //var data = 'calle='+variablecalle;
                    $j.ajax({
                            url: '../../updatesession.php',
                            type: 'POST',
                            data: data
                            }).done(function(data){
                            //append the recieved data on success
                            $j("#currSess").html(data);
                            $j("#currSess").html( $j("#currSess").text() );
                            var wrap = $j("#currSess");
                            var text = wrap.text();
                            wrap.replaceWith(text);

                            });
                });
                </script>

Would this work??? Ill test it in a sec

We are gettting somewhere.....

That code above sends

?><div id="currSess"></div><?php

To the webservice.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.