JPDP
JPDP

Reputation: 199

Send Session variable from Ajax to PHP

I have 4 buttons on a page that each have their own button. When the button is clicked the page does not refresh nor does it open a new page.

When a button is pressed I want to send the ID of that button via Ajax to a php file in the form of a session. Each of the 4 buttons have a different ID (1,2,3,4). If a user clicks one button and then a second button etc, I want to add each of the clicked button Id's into this session.

This is what I have so far:

Jquery:

     $(document).ready(function() {  
     $('a[name=add]').click(function(e) {
     session = $(this).attr('id')

     $.post('sessions.php', {session:session}
    );              
     });
     });

So that simply checks if a button with the name of "add" has been clicked (all 4 of the buttons have that name), and grabs the buttons ID and sends it to sessions.php

PHP:

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

Simply creates the session.

The problem I am having is that the PHP session is getting the ID of the first button clicked and that is all. If another button is clicked Ajax does post the button ID but the session only keeps the ID of the first button clicked.

How can I add the ID of the next buttons clicked to the session.

Example: If button 1 and 3 are clicked, I need the session to have ID 1 and 3.

Upvotes: 1

Views: 10253

Answers (3)

Lim H.
Lim H.

Reputation: 10050

<?php
    session_start();
    $id = $_POST['session']);
    if(!isset($_SESSION['ids'])) {
        $_SESSION['ids']= array();         
    }

    $_SESSION['ids'][$id] = $_POST['session']';
?>

Every time the AJAX request is made, your session id got reinitialized, hence in the end only one value remains. So you may want to create an array for session ids and every new id value get inserted into this array.

Upvotes: 1

Igor Parra
Igor Parra

Reputation: 10348

session_start();

// prepare $_SESSION['ids']
if ( ! is_array($_SESSION['ids']))
{
    $_SESSION['ids'] = array();
}

// fill $_SESSION['ids'] only with new $_POST['session'] posted
if ( ! in_array($_POST['session'], $_SESSION['ids']))
{
    $_SESSION['ids'][] = $_POST['session'];
}

Upvotes: 3

Jirilmon
Jirilmon

Reputation: 1944

This is because Jquery treats name or id as unique. Thats why your javascript function reads only first button.

Solution:

Use a common class name for the 4 buttons. (<a class="sessionclass otherclasses" href="#">1</a>)

Then change your jquery code:

 $(document).ready(function() {  
     $('a.sessionclass').click(function(e) {
         session = $(this).attr('id');    
         $.post('sessions.php', {session:session}
         );              
    });
});

Now your php session should set appropriate button value on click.

And I agree with @Lim H. Change your php code too like he suggested.

Upvotes: 2

Related Questions