Indra suandi
Indra suandi

Reputation: 161

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

Upvotes: 0

Views: 55

Answers (1)

Ammar Aslam
Ammar Aslam

Reputation: 670

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);
?>

Upvotes: 1

Related Questions