Would it be possible to pass the "Mage::getSingleton('core/session')->setTest()" object/method so the AJAX page itself can modify it? The problem is that the ajax page cannot access it (I think)

Nope, it cannot access it.

I have tried different things but no luck; Any ideas on how to do this?

url: '../../updatesession.php'

Have you tried a fully qualified URL (starting with http://)?

Have you tried a fully qualified URL (starting with http://)?

Firebug finds it and if I change its name, it says its not found so no, Im not making the same mistake twice :)

How can I use that "Mage::getSingleton('core/session')->setTest()" PHP object/method in Javascript? Possibly AJAX related but Im not sure how to do it.

There has to be some way to do this.

GOT it to work! :)

Just one problem; When I change the dropdown box to another value, the onchange events pops but it does not update the value.

What could be wrong?

Let me get some code up:

PHTML page:

<script type="text/javascript">
$j('#list').change(function() {
                    var variablecalle=$j("#listadetiendas").val();
                    alert ("i work");


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



                    $j.ajax({
                            url: '../../updatesession.php',
                            async: false,
                            type: 'POST',
                            cache: false,
                            data: data
                            }).done(function(data){
                                alert ("cambio el valor " + 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>

updatesession.php

<?php


    session_start();
    require '../app/Mage.php';
    Mage::app();


    Mage::getSingleton('core/session', array('name' => 'frontend'));
    Mage::getSingleton('core/session')->setBest($_POST['calle']);



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



?>

Then where I recieve the data (which is another page) I (strangly) have to put:

$calle=$_SESSION['calle'];

Using standard PHP session.....

The problem is now when I change what I selected in the dropdown list, it still passes the old value, not the new.

I dont understand why it doesnt work.

Any other hints/tips?

Now using that same code, it suddenly does not work.

In "updatesession.php" what am I suppose to "echo" back??? Honestly it makes NO sense to me and I cannot "logically" establish the session variable because I have no idea what it does....

Maybe starting with something simple and basic first will do the work.
Knowing you're already using something complex with the framework you're using, which is Magento's. It'll be harder for you to grok on its inner working. That framework, is a product of hardwork starting from the ground up. And, somewhere along the line they've committed mistakes after mistakes, failures after failures. For someone, who's using an epitome of success without the rudimentary experiences or the elementary knowledge of "failures" it's going to be hard tackling the big ones.

KISS principle applies here. So you have to land on your feet and start on the basic. Give that SESSION the last laugh. {GEEK TALK} LOL

Anyway, start with something simple and decript the problem starting from there.
Please check on this one if it kept on changing, if it does there's something impeding you on the part of saving your session ID. It will also show you where session is located.

<?php
    session_start();
    echo session_id();
?>
<script type="text/javascript">
    document.write("<br>IN COOKIE: " + document.cookie + "<br>IN URL: " + location.search);
</script>

If everything went well, go forward with ajax.
Hope that helps.

That prints out:

IN COOKIE: PHPSESSID=imoddsalej884u92d1scichlh1
IN URL: 

And now what?

By the way it should look like this:

imoddsalej884u92d1scichlh1
IN COOKIE: PHPSESSID=imoddsalej884u92d1scichlh1
IN URL: 

Shows the session id once the pages was retrieved from the server and the session ID stored in the cookie.
If it never changed then proceed with this:

test.php
<?php
session_start();
echo session_id();
sample.php
<?php
session_start();
?>
<!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(){
                $.ajax({
                    url: "test.php",
                    type: "GET"
                }).done(function(data){
                    $("#ajax-session").html("SESSION ID(ON AJAX): " + data);
                }).fail(function(){
                    alert("failed");
                });
            });
        </script>
    </head>
    <body>
        <div>
            <?php echo "SESSION ID(ON LOAD): " . session_id(); ?>
        </div>
        <div id="ajax-session"></div>
    </body>
</html>

This should give you a result like this one.

SESSION ID(ON LOAD): r1h27ttdr16up0lpego4s3ac06
SESSION ID(ON AJAX): r1h27ttdr16up0lpego4s3ac06

After then proceed to this:

test.php
<?php
session_start();
$_SESSION["FRUIT"] = isset($_POST["FRUIT"]) && !empty($_POST["FRUIT"])? $_POST["FRUIT"]: "";

echo '<div>SESSION ID: ' . session_id() . '</div>
        <div>FRUIT: "' . $_SESSION["FRUIT"] . '" </div>';
sample.php
<?php
session_start();
?>
<!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(){
                //Change this to see if it updates
                var fruit = "Mango";
                $.ajax({
                    url: "test.php",
                    type: "POST",
                    data: "FRUIT="+fruit
                }).done(function(data){
                    $("#ajax-session").html("<BR>RECIVED DATA " + data);
                }).fail(function(){
                    alert("failed");
                });
            });
        </script>
    </head>
    <body>
        <div>
            <?php echo "SESSION ID(ON LOAD): " . session_id(); ?>
        </div>
        <div id="ajax-session"></div>
    </body>
</html>

IF everything goes well up to this point. Then there's no problem with configurations on both your browser and server. Make sure to change the value(FRUIT) in the code, indicated by the comment. Also there's no issue with saving the data on a session thru ajax.

I was alerting it; I did it the same way you did and used those exact lines as the first in the file and correct it shows:

sjqh7d8lhhl84tn35k95uvd7e7
IN COOKIE: PHPSESSID=sjqh7d8lhhl84tn35k95uvd7e7
IN URL: 

Ill implent now your previous post and get back to you....

OK, i did it in a seperate folder and the first one gave the expected result and the second one:

 SESSION ID(ON LOAD): 4updnokejc27updjo5l1r32993

RECIVED DATA
SESSION ID: 4updnokejc27updjo5l1r32993
FRUIT: "Mango" 

So like you mentioned, server and browser seem to have no problems/issues.

So now what do I look for? This problem is so complex and Ive been at it for weeks :(

So these leads us to ether logic/design.
Let's compare that to you initial post. We'll focus on the script tag only. I'll be leaving some pointers which you can ponder at.

//Every explanations are isolated in this context only
<script type="text/javascript">
$j(document).ready(function() 
{
    // after the pages load, and there where still no interaction
    //  this line get's the value of $j("#listadetiendas")
    //  ISSUE: if you're getting a user input value of '#listadetiendas'
    //      the one sent thru ajax is the first value of '#listadetiendas'
    //      when the pages load. So if it starts with the value 5, the one will
    //      be sent to the server is the value 5 always. If the initial page load
    //      value of '#listadetiendas' is generated by PHP on page retrieval, then
    //      the value to be sent is the generate value.
    var variablecalle=$j("#listadetiendas").val();

    var data = 'calle='+variablecalle;

    // There will be an ajax request on page load. Since your url in your config
    //  shows a relative path, the ajax will send the data to the page 2 
    //  levels down.
    //  Meaning, if you have this page page at
    //  "http://localhost/folder1/folder2/folder3/index.php"
    //  ajax will lookup at 
    //  "http://localhost/folder1/updatesession.php" If this page is located at
    //  "http://localhost/index.php", it will look up at 
    //  "http://localhost/updatesession.php"
    //  negating the levels it should traverse.
    //  ISSUE: Since you got the value of '#listadetiendas' sent after the 
    //      dom completes loading then expect the sent value to be the initial 
    //      value of '#listadetiendas'. Unless programmatically changed. Also, 
    //      if the AJAX url does not exist, since you're using a relative URL, 
    //      you won't be able to talk to the right page.
    $j.ajax({
        url: '../../updatesession.php',
        type: 'POST',
        data: data
    });
});
</script>

For the updatesession.php

<?php
    session_start();
    // Once the ajax sent a request it will be put to 'calle'
    //  and save to session.
    //  ISSUE: What if there where no value in '$_POST['calle']'
    //      how would the script handle that?
    $_SESSION['calle']=$_POST['calle'];

Asside from jQuery, are you using other frameworks, on both php and JS?
And how come Magento came in to play, was the code for a magento project?

Everytime the pages loads up, two things happen:

1: A dynamic (eg. PHP) drop down menus is created with values from a database.
2: The document ready function gets that value.

They are also executed in this order because the document read does indeed get the value.

This line you said:

So if it starts with the value 5, the one will
// be sent to the server is the value 5 always.

This is something similar to what happened initially. I changed the value, the drop down changed event shot out, but even if it changed, the initial value was still the same. I copy/pasted the code between doc ready and dropdown change because they are going to do the same thing.

Ive changed it between the absolute path and the relative path; Both give the same results. I know I am editing the correct file because there are changes (the output of echo for example)

$_POST['calle'] will ALWAYS have a value. Its a dropdown menu.

Personally, no. jQuery is declared as $j because Prototype uses $. Prototype is there because Magento uses it.

This code is for use in a Magento project.

What do you want me to do now? I can do back to that initial post and we can try again...

The odd thing is that it was working at one point; I tried the changing event but it only got me first and initial value....

There are three pages involved here:
billing.ptml - This is where the drop down box is populated and intially gets it value from. Here there is the PHP function that loads the dropdown box with values. Also, the javascript function here that calls the AJAX page is here.
updatesession.php - This is used for the AJAX page. This sets the session variable and echos something (what, I do not know) back
Observer.php - This is what calls the webservice and sends the data to it.

billing.phtml and Observer.php are both part of Magento.

Thank you for your help. What else can I do?

Correct me if I'm wrong. What you wanted was to send an ajax request based on the dropdown's value?

If so, then a step like this would be ok:

STEP 1

(Page before billing.ptml) do form fill up

isset($_SESSION["calle"]) === TRUE

Session variable 'calle' doesn't exist yet.

STEP 2

billing.phtml - initial load

isset($_SESSION["calle"]) === TRUE && $_SESSION["calle"] === ['#listadetiendas' initial value]

The billing.phtml sent the initial value of Session 'calle' on its initial load.

STEP 2

billing.phtml - '#listadetiendas' on change

isset($_SESSION["calle"]) === TRUE && $_SESSION["calle"] === ['#listadetiendas' selected value]

The billing.phtml sent a new value for Session 'calle' when a new option in '#listadetiendas' was selected.

Let me know if this script suffice, or still doesn't go with the requirement

<script type="text/javascript">
$j(document).ready(function() {
    // Send the initial value of '#listadetiendas' when
    //  the DOM fully loads
    var data = 'calle=' + $j("#listadetiendas").val();
    $j.ajax({
        url: '../../updatesession.php',
        type: 'POST',
        data: data
    });

    // On the event the value of '#listadetiendas' changes
    //  make another AJAX call and send the new value of
    //  '#listadetiendas'
    $j("#listadetiendas").on("change",function(){
        var data = 'calle=' + $j("#listadetiendas").val();
        $j.ajax({
            url: '../../updatesession.php',
            type: 'POST',
            data: data
        });
    });
});
</script>

For the 'updatesession.php'

<?php
    session_start();
    $_SESSION['calle']=isset($_POST['calle']) && !empty($_POST['calle'])?$_POST['calle']:"";

let me know if that helps. Just change the url in both ajax func config if not appropriate.

Correct me if I'm wrong. What you wanted was to send an ajax request based on the dropdown's value?

What I want is a session variable that is visible accross all of the site. I dont care if its a AJAX request or if I have to do it in Flash :P

Im sorry but I believe you are going to have to reexplain...

STEP 1:
(Page before billing.ptml) do form fill up

isset($_SESSION["calle"]) === TRUE

Session variable 'calle' doesn't exist yet.

Do you want me to simply put:

<?php isset($_SESSION["calle"]) = TRUE ?>

And thats it? I thought isset was usually used in a if....

STEP2:

I imagine that you simply want to me to load the dropdown box and then assign directly the session variable to the first value. This is no problem.

STEP2 (which I imagine is 3):

In the JS side, currently everything is how you put it. Ill put what you put on the PHP side.....

I just need to clear STEP1 up a bit as I do not understand what you mean.

Thank you.

Another thing, do I include the "onchange" in the document ready function? I had

document ready
start ready
finish ready

change
start change
finish change

Do you want me to do:

document ready
start ready

change
start change
finish change

finish ready

Ive done step 1 and now the session variable eaches the "end". It exists.

Now I have to play with it in AJAX.....

Hi Riahc3,

isset($_SESSION["calle"]) === TRUE I forgot to tell these are just representation of $_SESSION['calle']'s state. and the 1st step is just an imaginary page before going to step 2, where you put a value to $_SESSION['calle']

Anyhow, all through out the life time of $_SESSION['calle'], at its initial declaration, depending on your specs, should it have an initial value or a garbage value?
in your ajax code you can remove the automatic sending of value, and leave the onchange event handler. This will leave the application to populate $_SESSION['calle'] only when the user interacts with '#listadetiendas'.

<script type="text/javascript">
$j(document).ready(function() {
    $j("#listadetiendas").on("change",function(){
        var data = 'calle=' + $j("#listadetiendas").val();
        $j.ajax({
            url: '../../updatesession.php',
            type: 'POST',
            data: data
        });
    });
});
</script>

and this:

<?php
    session_start();
    $_SESSION['calle']=isset($_POST['calle']) && !empty($_POST['calle'])?$_POST['calle']:"";

Man this is stressful..........

Now I have to play with it in AJAX.....
That "imaginary page" (the page before billing.pthml) is sorta a resume of the cart. I put it there as:

<?php
if(isset($_SESSION['calle']))
 $_SESSION['calle']=$_SESSION['calle'];
 else
 $_SESSION['calle']="im session";
?>

At its initial value, no, it should have nothing. It should just load what is in the dropdown box and refresh when it is changed.

Basically copying/pasting that code you put and see if it works.

Nope........nothing. Did this, selected somethinf from the dropdown (trigging on change) and nothing

BTW, if there are any alternative ideas to this (carry a value thruout a site) Id be happy to hear.

Im currently looking at this: http://samy.pl/evercookie/

Member Avatar for diafol

Evercookie - looks intrusive - I don't think I'd want it on my machine. Persisting data should be done with sessions IMO.

The issue here is not the code we're looking at. The previous code I gave you, as you said, worked. We can take out the issue of having a persistent storage for calle, those codes are intended to prove that the session retains.

There's quite a small opening for us to conclude the problem here was recent code we have, since the posted code, already works. The issue was there's a part of you code or process that changes and the session calle also. And I assume it was another framework.

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.