convert array into json using php , and retrive json using jquery or javascript

75 views Asked by At

I created json using php:

 $arr = [];
    foreach($userinfo as $record) {
        $arr[] = array(
           'BAid' => $record->getBAid(),
           'BCid' => $record->getBCid(),
          'BAusername'=>$record->getBAusername(),
          'BAdisplay_name'=>$record->getBAdisplay_name(),
          'BAtel'=>$record->getBAmobile(),
          'BAimg'=>$record->getBAimg(),
          'BArole' => $record->getBArole()
      );}

    echo json_encode($arr);

and I used the following code to retrieve the result of json, and I want to put it inside the html table.

 $.ajax({
            url :"admin=search",
            type: "POST",
            data: {search:name },
            success: function (data) {
              //  alert(data);
                const myArrStr = JSON.stringify(data);

                console.log(data);

            }
        })
2

There are 2 answers

1
AudioBubble On

Try and use:

var data_array = JSON.parse(data);

This will return the json in a javascript array. Then you can use data_array.BAid for example to output the data.

EDIT: If this does not help you, take a loot over here: https://stackoverflow.com/a/8823991/10791031

1
Hamza Waleed On

You've to set headers to tell the browsers that requested endpoint is returning a json response. So you can use the below code to set the headers.

$data = $arr
header('Content-Type: application/json');
echo json_encode($data);