Reputation: 1520
I've used php's json_encode()
function many times, but for some reason I can't seem to find the problem here...
Note: I've removed error checking for clarity purposes.
//PHP
<?php
session_start();
require 'global/query.php';
$sql = "SELECT sfl,station,latitude,longitude,address,city FROM maps";
$stmt = $pdo->prepare($sql);
$stmt->execute();
while($result = $stmt->fetch(PDO::FETCH_ASSOC)){
$trows[] = $result;
}
echo json_encode($trows);
?>
I'm using AJAX and am just console.log()
-ing the output to print the response like so...
//JS
var callback = {
"projects": function(e){
console.log(e.target.response);
}
};
In the console it prints a blank line with none of the data...
Now if I var_dump
the $trows
the output in the console will print the data so I know my sql statement works just fine...
//PHP
var_dump($trows);
//CONSOLE
array(522) {
[0]=>
array(6) {
["sfl"]=>
string(1) "1"
["station"]=>
string(26) "COMPRESSOR STATION"
["latitude"]=>
string(2) "23"
["longitude"]=>
string(4) "-115"
["address"]=>
string(10) "Unnamed Rd"
["city"]=>
string(9) "blah"
}
[1]=>
array(6) {
["sfl"]=>
string(1) "2"
["station"]=>
string(17) "STA TERMINAL"
["latitude"]=>
string(2) "16"
["longitude"]=>
string(4) "-101"
["address"]=>
string(11) "15 Ranch Dr"
["city"]=>
string(8) "Blah Blah"
},
Questions: Why isn't my php's json_encode function working? I've used this exact code before and the output was fine.
Upvotes: 2
Views: 1648
Reputation: 757
Try and add:
header("Content-type: application/json; charset=utf-8");
Before you echo your JSON encoded result.
EDIT:
If the encoding doesn't work try the following:
while ($result = $stmt->fetch(PDO::FETCH_ASSOC))
{
$trows[] = array_map('utf8_encode', $result);
}
Upvotes: 3
Reputation: 64657
I would see what PHP tells you:
Change
echo json_encode($trows);
to
$json = json_encode($trows);
$error = json_last_error();
if ($error !== JSON_ERROR_NONE) {
echo json_last_error_msg();
} else {
echo $json;
}
Upvotes: 1