3

I would like to convert a JS array to a PHP array. I tried to send the value to the PHP page:

var seatsReserved = [];

function reserve(seat) {
    seat.setAttribute("class", "reserved");
    var hasClass = seat.classList.contains('reserved');
    if (hasClass) {
        seatsReserved.push(parseInt(seat.innerHTML));
        $.post('../index.php', {
            'seatsReserved': seatsReserved
        });
        console.log(seatsReserved.sort(function(a, b) {
            return a - b
        }));
    }
}

However, when I run

$seatsReserved = $_POST['seatsReserved'];

I get this error:

Notice: Undefined index: seatsReserved

How can I correctly pass the array to PHP?

APerson
  • 8,140
  • 8
  • 35
  • 49
  • 1
    you need to serialize array into string `JSON.stringify(seatsReserved)` – monkeyinsight Oct 19 '14 at 01:21
  • Look at the Network tab in your browser. You can see what is actually sent there. jQuery might not encode/format it correctly. – Rudie Oct 19 '14 at 01:22
  • Btw: how do you know what the server says? You're not listening for a response.... – Rudie Oct 19 '14 at 01:23
  • `$.post('../index.php', { 'seatsReserved': JSON.stringify(seatsReserved) });` is it the correct way to serialize and send it? – user2805212 Oct 19 '14 at 01:42
  • Yup, that looks good. Then on the server you need to use json_decode to convert it into a PHP array. – Shomz Oct 19 '14 at 01:45
  • `$seatsReserved = json_decode($_POST['seatsReserved']);` I used this function but I still get the error: `Undefined index seatsReserved` – user2805212 Oct 19 '14 at 01:48
  • Convert it into json before you send it out. and inside php, you can convert the json into php array by json_decode($_POST['seatsReserved']) – Sandun Perera Dec 20 '19 at 12:50

0 Answers0