简体   繁体   中英

Pass integer from jQuery to PHP Session array

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!

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'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM