Reputation: 639
Please, is there someone who can shine me a light on this issue?
I'm sending an ajax request to a php file. Everything was ok until I changed dataType from 'html to 'json'.
In the attempt to debug, I started to put these 3 lines of code after certain points in the php file :
header('Content-type: application/json');
echo json_encode(Array('message' => 'success'));
die();
This is what I found:
I can't use require_once to require classes but I can only use include: in the first case ajax gives me error, in the second it gives me the message 'success' as it should.
I can't use global variables within php file, only default variables.
I can't use the static methods of the classes previously included like MyClass::myStaticMethod(), only instances.
Maybe other things I've not yet discovered...
Is this normal or am I doing something wrong? Where can I find a list of php features that I can't use? Is there a way to overcome the problem since I need those features?
Upvotes: 1
Views: 628
Reputation: 6513
On server side you can do whatever you want as long as you respect the rules of JSON.
As a methodology, you can start building an static JSON file that works. Then piece by piece replacing its parts with the equivalent generated by PHP, that means (and is limited to), headers and content
On browser side, what you need is a predefined format (the output of your PHP script), there is no way to know if required_once or global variables were used.
Upvotes: 1
Reputation: 598
All you need to do on the server side is to set the content-type to application/json, encode your data using the json_encode function and output it.
<?php
header('content-type: application/json; charset=utf-8');
$data = array(1, 2, 3, 4, 5, 6, 7, 8, 9);
echo json_encode($data);
?>
You can test it out for example in console by running this line:
$.ajax({url: 'data.php'})
// Response: [1,2,3,4,5,6,7,8,9]
Let me know if u finding difficulty.
Thanks
Upvotes: 0
Reputation: 613
Take a look
<?php
//1st Situation
header('Content-type: application/json');
echo json_encode(Array('message' => 'success'));
?>
//respective JS would be
<script>
var json = ajax_response;
</script>
<?php
//2nd Situation with no content header (html default)
echo json_encode(Array('message' => 'success'));
?>
//respective JS would be
<script>
var json =$.parseJSON(ajax_response);
</script>
Upvotes: 0