0

I am trying to pass an integer from jQuery to a Session array in PHP. I have a button with an id, this id should be added to the session array.

I started the session with:

// ADD SESSION START TO HEADER
function hook_session() {
if(session_id() == ''){
     session_start(); 

     $parts=array();

     $_SESSION['parts']=$parts;
}    
}
add_action('wp_head', 'hook_session');

My jQuery:

$('.product-button').click(function(){
    $id = $(this).val();
    $id = parseInt($id);
    $.ajax({
        url: ajaxurl,
        type: 'POST',
        data: $id,
        dataType: 'jsonp',
        success: function (result) {
            console.log('Yay it worked');
        },
        error: function (xhr, ajaxOptions, thrownError) {
            console.log('Something went wrong');
        }
    });
});

my PHP:

<?php
array_push($_SESSION['parts'],$_POST[$id]);
print_r($_SESSION['parts']);?>

Where am i going wrong? Thanks!

2
  • I think you should edit your post to provide a little more information - like: What are the results of this code? Do you see your "Yay it worked" message in the console or "Something went wrong"? Is the array populated or no? Also, what is ajaxurl, presumably you're sure you're posting back to the PHP page? Commented Aug 9, 2017 at 13:34
  • @DaveyDaveDave When I run the function I get "Something went wrong". ajaxurl is a jquery var which contains the url to the php file which contains the php in my original post. Commented Aug 10, 2017 at 8:24

1 Answer 1

3

You didn't give a name to the POST parameter.

$.ajax({
    url: ajaxurl,
    type: 'POST',
    data: { id: $id },
    success: function (result) {
        console.log('Yay it worked');
    },
    error: function (xhr, ajaxOptions, thrownError) {
        console.log('Something went wrong');
    }
});

Then in the PHP, use $_POST['id'] to access the parameter.

<?php
session_start();
array_push($_SESSION['parts'],$_POST['id']);
print_r($_SESSION['parts']);
?>

Also, print_r() doesn't produce JSONP format output, so don't use dataType: 'jsonp'

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.