Reputation: 23
I'm making a query to the database and the query is successfull. I create an array where I put the values of the result of the query and then I return the json_encode of the array.
$i=0;
while($row=$result->fetch()){
$Invoices[$i]=Array("InvoiceNo"=>$row['InvoiceNo'],"InvoiceDate"=>$row['InvoiceDate'],"CompanyName"=>$row['CompanyName'],"GrossTotal"=>$row['GrossTotal']);
$i++;
}
if($i==0)
echo json_encode($empty_array);
else
echo json_encode($Invoices);
This works in google chrome, I have the json viewer and it formats correctly, but in firefox it doesn't show as json. And when I try to parse it it doesn't work. Tried with $.Ajax and $.getJSON
Upvotes: 1
Views: 1780
Reputation: 30071
You can always try to set the content type using a header()
call, add the following to the top of the page, before any output:
header("Content-Type: application/json");
You should also make sure that you don't have any empty space before you're actual php code because that will also be sent in the result and may interfere with your json response.
In the ajax call you can set the dataType
to json
like this:
$.ajax({
url:"<example.com/index.php>",
dataType:'json',
success:function(e) {
// e now should contain your json data
}
);
Note that:
"json": Evaluates the response as JSON and returns a JavaScript object. The JSON data is parsed in a strict manner; any malformed JSON is rejected and a parse error is thrown. As of jQuery 1.9, an empty response is also rejected; the server should return a response of null or {} instead. (See json.org for more information on proper JSON formatting.)
Upvotes: 3