Reputation: 33
Im using a basic jquery
ajax
call.
I make a call to a php
file without input parameters with option datatype set to json
.
I want the server to parse the php
which queries a table in a mysql
db, convert it to array
and finally encode
it to json
and return
.
I tried a test call from the browser by copying the php
file url
in the address
field, and it shows that it works, since I can see a blank page with all the rows of the table in json
formatting.
Instead, when calling from my javascript
code the $.ajax
call fails with error
Requested JSON parse failed
which means ajax
call was expecting json
(since I set option datatype to that) but received another format.
So I tried removing the datatype option from the call, and lo and behold I got a response success
, but what did I received from my php
file?
Well, it was the whole code in the file, like the server doesn't parse it cause it thinks it's plain text.
Is there a way out of this problem? Thanks.
Upvotes: 0
Views: 146
Reputation: 33
I'm an idiot, I may answer my own question, I was debugging jquery from visual studio, which automatically instatiates an iis web server, and it explains why it was treating php files like text files. Obviously under apache everything works fine. Sorry for taking your time....
Upvotes: 0
Reputation: 3780
The ajax function is expecting a JSON encoded document so you have to send a header with the response saying that the response contains JSON. Something like this:
<?php
header('Content-Type: application/json');
// All your code here
echo json_encode($someArray);
?>
Upvotes: 1
Reputation: 3786
Send also content header with json data
<?php
header('Content-Type: application/json');
echo json_encode($data);
Upvotes: 2