1
$AllSorts = array();
$AllSorts[] = array('type'=>'العدد الكلي','num'=>$allSize);

$AllSorts[] = array('type'=>'عدد الطلاب','num'=>$studentSize);

$AllSorts[] = array('type'=>'عدد الأساتذة','num'=>$tchSize);

$AllSorts[] = array('type'=>'عدد المدراء','num'=>$managerSize);

$AllSorts[] = array('type'=>'عدد مراقبي الدوام','num'=>$atsSize);

$AllSorts[] = array('type'=>'عدد مراقبي الحافلات','num'=>$bgrSize);

$AllSorts[] = array('type'=>'عدد مراقبي الرسوم','num'=>$fgrSize);


$JsonData = json_encode($AllSorts);
echo $JsonData;

this is the php code to get thw json date

var jsonData = '';
    
$.get('../Functions/Ajax/GetSortingData.php?id='+schoolId, function(data){
            jsonData = JSON.parse(data);
    console.log(jsonData);
    
       });
var labels = [];
var datas = [];
for(const obj of jsonData){
   labels.push(obj.type);
   datas.push(obj.num);
}
console.log(datas);

and this is the javascript

2 Answers 2

1

Use map:

const array = [{
    type: "العدد الكلي",
    num: 14
  },
  //.snip
]

const type = array.map(i => i['type'])
console.log(type)

const num = array.map(i => i['num'])
console.log(num)

Sign up to request clarification or add additional context in comments.

Comments

0

Just loop over the array of objects.

var arr = [
  {type: "العدد الكلي", num: 14},
  {type: "عدد الطلاب", num: 8},
  {type: "عدد الأساتذة", num: 2},
  {type: "عدد المدراء", num: 1},
  {type: "عدد مراقبي الدوام", num: 1},
  {type: "عدد مراقبي الحافلات", num: 1},
  {type: "عدد مراقبي الرسوم", num: 1}
];
var labels = [];
var datas = [];
for(const obj of arr){
  labels.push(obj.type);
  datas.push(obj.num);
}
console.log("Labels", labels);
console.log("Datas", datas);

For your particular case, you need to be looping over the array in the callback for the AJAX call, as AJAX is asynchronous.

$.get('../Functions/Ajax/GetSortingData.php?id='+schoolId, function(data){
            jsonData = JSON.parse(data);
            console.log(jsonData);
            var labels = [];
            var datas = [];
            for(const obj of jsonData){
               labels.push(obj.type);
               datas.push(obj.num);
            }
            console.log(datas);
       });

16 Comments

@R4EGroup What do you mean? The array is empty after?
no error just give 0 size of the labels and datas array
@R4EGroup What exactly does your JSON data look like? Is it an array of objects?
@R4EGroup Are you trying to parse the JSON as a string?
my json is a string i get from php ajax then i do json.parse to it
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.