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?

11
  • 1
    What the result is if you access drivetracker2.php in browser? Commented Mar 19, 2013 at 9:13
  • The code you posted looks good to me. Are you trying to access data anywhere else? Commented Mar 19, 2013 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. Commented Mar 19, 2013 at 9:17
  • @pktangyue it does not output anything on drivetracker2.php Commented Mar 19, 2013 at 9:20
  • @felix no it does not. console.log(data) in javascript Commented Mar 19, 2013 at 9:20

2 Answers 2

1

Try this

 $.post('drivetracker2.php', function(data) {
  console.log(data);
 },'json');
Sign up to request clarification or add additional context in comments.

4 Comments

Why should this make a difference? Please explain.
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: 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.
I didn't see the $.getJSON part. In that case there is indeed no difference other than the type of the HTTP request :/
1

Add this just before you echo the json.

header('Content-Type: application/json');

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.