0

I have the following in a js script:

let skippers = {};
for(let i = 0; i < skipperIds.length;i++){
    skippers[skipperIds[i].value] = skipperIds[i].checked;
}

regData.skippers = skippers;          
responseData = sendData2('https://sailwbob.com/lagin/public/register.php',regData);

where sendData2 is an async call using axios. skippers looks like

{1:true,20:false}

In my php file I have:

$skippers = ($_POST['skippers']);           
            
$skipperIds = array_keys($skippers);
$skipperValues = array_values($skippers);

but this is not working. I think php converts an array in $_POST to a string but I'm not sure.

two qustions:

  1. how do I convert $skippers back to an array?
  2. I've been trying to use print_r to see the data on the server but as this is an async call it's not working as the print_r results are being sent back to the js script and not printing out on the screen. Is there a way to see the results of print_r?

Update:

I tried $x=json_decode($_POST); but got an error saying it was expecting a string.

here's the call to axios:

function sendData2(url,emailPass){

    let bodyFormData = new FormData()
    for (const [key, value] of Object.entries(emailPass)) {
        //console.log(key,value)
        bodyFormData.append(key,value)
    }

    return axios({
            method: 'POST',
            url: url,
            data: bodyFormData,
            headers: {'Content-Type': 'multipart/form-data'}
            })
                .then(function(response){
                    return response.data
                })
                .catch(function(response){
                    return response
                })
}

update2:

$skippers shows $skippers = [object Object]. Is there a way to send this to the server correctly?

RiggsFolly
  • 93,638
  • 21
  • 103
  • 149
DCR
  • 14,737
  • 12
  • 52
  • 115

2 Answers2

0

As discussed in this article, axios serializes Javascript objects to JSON and becase PHP doesn't support JSON as a data format for populating $_POST, you can retrieve them in PHP like this:

$_POST = json_decode(file_get_contents("php://input"),true);
$skippers = $_POST['skippers'];
Kinglish
  • 23,358
  • 3
  • 22
  • 43
0

While axios does automatically stringify data it apparently doesn't do that for nested arrays. I needed to add:

 regData.skippers = JSON.stringify(skippers); in my js 

and then in the php file

$skippers = get_object_vars(json_decode($_POST['skippers']));
DCR
  • 14,737
  • 12
  • 52
  • 115