0

I'm trying to send an array to JS, but I can't get the array I want.

This is my Controller PHP code:

foreach ($test as $k => $subArray) {
   foreach ($subArray as $id=>$value) {
      array_key_exists( $id, $sumArray ) ? $sumArray[$id] += $value : $sumArray[$id] = $value;
   }
}
array_push($t, $sumArray);
$data['res'] = array_values($t[0]);
array_push($temp, $data);
echo json_encode($temp);

The output was:

[{"res":[484603732,350203732,133347732,203347732]}]

This is my View code:

$.get('/index.php/dashboard/linechart', function(data){
     console.log(data.res);
});

My expected output on console.log was:

[484603732,350203732,133347732,203347732]

but something goes wrong, the output went undefined.

So far I've tried with JSON.parse(data.res);

But still got undefined.

Anyone could save my day? I'm really stuck with this.

9
  • 1
    You've to parse data to an object, your server sends a JSON string. Notice also, that res is a member of the array, hence data[0].res is what you need. Commented Sep 6, 2019 at 4:13
  • Could you please show me how to do it? Coz I've tried all of the methods I know. But still, it goes error. Commented Sep 6, 2019 at 4:16
  • This should not be extremely hard, take some time, examine carefully what you have written and what kind of results you're having, and re-read my comment, practically the code you need is in that comment. Commented Sep 6, 2019 at 4:19
  • 1
    What about response = JSON.parse(JSON.stringify(data)); alert(response); for(var i in response){ alert(response[i].res); } Commented Sep 6, 2019 at 4:27
  • 1
    let parsedData = JSON.parse(data); let res = parsedData[0].res; should do. Server always responses with a string, live objects are not going through the http(s). Commented Sep 6, 2019 at 4:27

1 Answer 1

1

As per your output:

[{"res":[484603732,350203732,133347732,203347732]}]

The issue is with the response. You're returning an array and not an object. So your ajax should be doing something like this:

$.get('/index.php/dashboard/linechart', function(data){
 actualData = JSON.parse(data); 
 console.log(actualData[0].res);
});
Sign up to request clarification or add additional context in comments.

3 Comments

Uncaught SyntaxError: Unexpected end of JSON input
Hi, can you just log data and show the output.
If I'm trying to console.log(data), the output was empty.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.