简体   繁体   中英

how to Receive JSON data sent by ajax in PHP

I have the data that want sent to backend, its look like

function lihat(){
    let id = "12345678";
    let profile = [{name:"dave", department : "Engginering"},
                   {name:"Tedd", department : "Engginering"}]
    $.ajax({
        type:'POST',
        url:'pages/dashboard/dashboard_be.php'
        data:{
            cekload  : true,
            keys     : id,
            dataList : profile 
        },
        success:function(data){
            console.log(data);
        }
   })

the question, how can I receive all of datas sent by ajax in php script this what I've tried

    $id      = $_POST['keys'];
    $cekload = $_POST['cekload'];
    $data    = json_decode($_POST['dataList'];);

   //I wanna parsing the dataList object and then loop it, how to make it ?

thanks, before

If you're trying to send/receive javascript objects, you need to convert the object to a string before sending and decode it back in php (into an array maybe) before reading.

<script>
    let id = "12345678";
    let profile = [{name:"dave", department : "Engginering"},
                   {name:"Tedd", department : "Engginering"}]
    $.ajax({
        type:'POST',
        url:'pages/dashboard/dashboard_be.php',
        data:{
            cekload  : true,
            keys     : id,
            dataList : JSON.stringify(profile) 
        },
        success:function(data){
            console.log(data);
        }
   });
</script>

PHP code:

<?php 
$id = $_POST['keys'];
$cekload = $_POST['cekload'];
$data = json_decode($_POST['dataList'], true);

echo $id;
echo $cekload;
print_r($data);
?>

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