Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

Hugo Paz
Hugo Paz
15,622 Points

Extracting array values in PHP session variable with Ajax

I want to display a cart which is saved in a session variable. I want to do it on hover so I'm using jQuery.

This is a test example:

On my test page i have:

session_start();
$_SESSION["test"] = array("one", "two", "three");

On my getsession.php i have:

session_start();
if (isset($_GET['requested'])) {
    // return requested value
    print json_encode($_SESSION[$_GET['requested']]);
} else {
    // nothing requested, so return all values
    print json_encode($_SESSION);
}

And on my app.js i have:

//get session data
var session;

$("#getSession").click(function (){

$.ajaxSetup({cache: false});
$.get('getsession.php', {requested: 'test'}, function (data) {
    session = data;
    $("#sessionContent").append(session);
});
});

When i click the button to test the result i get ["one","two","three"]

If i try $("#sessionContent").append(session[0]);

I get [

How can i access each individual value on the array?

1 Answer

Chris Shaw
Chris Shaw
26,676 Points

Hi Hugo,

By default GET requests use the content-type text/plain, what you want is application/json which you can achieve by setting an 4th argument in the $.get method call as I've done below, now you will have access to an array and not just a string.

$.get('getsession.php', {requested: 'test'}, function (data) {
    session = data;
    $("#sessionContent").append(session[0]);
}, 'json');
Hugo Paz
Hugo Paz
15,622 Points

Worked perfectly. Thank you for your help.