0

in php

<?php
    $arr = array ('a'=>1,'b'=>2,'c'=>3,'d'=>4,'e'=>5);
    echo json_encode($arr); // {"a":1,"b":2,"c":3,"d":4,"e":5}
?>

in javascript,

$.getJSON('drivetracker2.php', function(data) {
    console.log(data);
});

I am trying to access the php array which was sent via json to javascript.
but it says data is undefined.
anyone know why and how to fix this problem?

ealeon
  • 12,074
  • 24
  • 92
  • 173

2 Answers2

1

Try this

 $.post('drivetracker2.php', function(data) {
  console.log(data);
 },'json');
Kathiravan
  • 689
  • 1
  • 7
  • 22
  • Why should this make a difference? Please explain. – Felix Kling Mar 19 '13 at 09:14
  • 2
    You need to specify in what format the response is going to be sent. Here he is saying Jquery that "the response I'm waiting for, is a JSON string", so it will be parsed to a JSON object automatically – Loupax Mar 19 '13 at 09:16
  • @Loupax: Was this directed at me? `$.getJSON` also tells jQuery to treat the response as JSON. There is no difference to the OP's code, only that it is POST instead of GET. – Felix Kling Mar 19 '13 at 09:30
  • I didn't see the `$.getJSON` part. In that case there is indeed no difference other than the type of the HTTP request :/ – Loupax Mar 19 '13 at 10:11
1

Add this just before you echo the json.

header('Content-Type: application/json');
karmafunk
  • 1,453
  • 12
  • 20