0

I've got a problem with the interaction between PHP and JavaScript via JSON.

The PHP-Script reads data from my database. The SQL result consists of 1 row.

name | lat | lng


Kilian | 45.1252335 | 32.2142380

It is encoded into JSON:

$query = "SELECT name, lat, lng FROM location l, user u WHERE u.email = l.email";
$result = mysqli_query ($dbc, $query) or die ('Error querying database.');
$to_encode = array();
while($row = mysql_fetch_assoc($result)) {
    $to_encode[] = $row;
}
echo json_encode($to_encode);

The JavaScript program loads the JSON file from the php-script (get_locations.php):

$.getJSON('get_locations.php', function (data) {
        $.each(data, function(i, name) {
            alert(name.parent_level);
        });
    });

But there is no alert in the browser. If i inspect the sent JSON in Chrome it just says []. How can i get to the sent name, lat and lng?

Edit: The real world output of get_locations.php is []. Converting the JSON to string always resulted in [].

2
  • You are sure and have checked that the query has results? If so, try with pushing elements to $to_enconde using an index instead of [] (For some reason, json_encode does weird things with that). Commented Apr 21, 2013 at 19:24
  • Could you add some real world output from get_locations.php? In javascript console.log(data) could also help. Commented Apr 21, 2013 at 19:24

1 Answer 1

2

You are mixing functions:

$query = "SELECT name, lat, lng FROM location l, user u WHERE u.email = l.email";
$result = mysqli_query ($dbc, $query) or die ('Error querying database.');
$to_encode = array();
while($row = mysql_fetch_assoc($result)) {
    $to_encode[] = $row;
}
echo json_encode($to_encode);

You create a mysqli query, so you should get the result with mysqli_fetch_assoc rather than the mysql_ version.

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

1 Comment

You are welcome! Don't forget to click the check mark next to answers that get things working for you for future questions as well. ^^ (You also get rep for doing it and would make those helping you in the future more willing to do so.)

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.