Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

This question already has an answer here:

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?

share|improve this question
1  
What the result is if you access drivetracker2.php in browser? – pktangyue Mar 19 at 9:13
The code you posted looks good to me. Are you trying to access data anywhere else? – Felix Kling Mar 19 at 9:15
If you're using a modern browser such as Chrome/Firefox, you should be inspecting the request with your development tools. This will allow you to determine whether the request is sending/receiving correctly. – juco Mar 19 at 9:17
@pktangyue it does not output anything on drivetracker2.php – ealeon Mar 19 at 9:20
@felix no it does not. console.log(data) in javascript – ealeon Mar 19 at 9:20
show 6 more comments

marked as duplicate by Till Helge, dragon112, N̨ul̕L͑P̯͍̭ȏͣ͛iƞer, Yogesh Suthar, Ocramius Mar 19 at 9:17

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

2 Answers

Try this

 $.post('drivetracker2.php', function(data) {
  console.log(data);
 },'json');
share|improve this answer
Why should this make a difference? Please explain. – Felix Kling Mar 19 at 9: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 at 9: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 at 9: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 at 10:11

Add this just before you echo the json.

header('Content-Type: application/json');
share|improve this answer

Not the answer you're looking for? Browse other questions tagged or ask your own question.