1.11M Members

AJAX setting session variables doesnt work.

 
0
 

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'];
?>
 
0
 

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.

 
0
 

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());

?>
 
0
 

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);

 
0
 

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.

 
0
 

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']:'') .'"}';
 
0
 

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']:'') .'"}';


?>
 
0
 

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

 
0
 

I put a alert(data); before

var retData = JSON.parse(data);

And it returns nothing. Empty.

 
0
 

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

 
0
 

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?

 
0
 

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.

 
0
 

Change that and now it gives me:

TypeError: retData is null

if(retData.sessID != currentSessionID)

 
0
 

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 ||

 
0
 

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.

 
0
 

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>
 
0
 

Thank you pritaeas and gon1387.

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

Might take a minute or two.

 
0
 

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

 
0
 

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.

 
0
 

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']";
You
This question has already been solved: Start a new discussion instead
Post:
Start New Discussion
Tags Related to this Article