i'm a little bit confused here. i've PHP file that retrieve database records . i'll call it with an Ajax call from my frontend . do i need to convert the records to JSON ? if no when do i need to do that
-
3You should convert some of your questions to be accepted. – David Hoerster Aug 16 '11 at 18:49
-
Similar: http://stackoverflow.com/questions/4881876/why-need-to-use-json-in-php-and-ajax/4881898#4881898 – Chris Laplante Aug 16 '11 at 18:52
-
my apologize !! that question is exactly what i need . close the topic or delete it if u want ! Apologize again – Iyad Al aqel Aug 16 '11 at 19:01
3 Answers
You don't "need" to return the results as JSON. But I would recommend it. JSON is very portable, so it will be easier for other applications to interact with your application. It's also much easier to parse JSON than it is records separated by simple delimiters.
For example, you can use Crockford's JSON parser: http://www.json.org/js.html
As for JSON vs XML: Why need to use JSON in php and AJAX

- 1
- 1

- 29,338
- 17
- 103
- 134
You don't have to use JSON but you can encode any associative array using the function json_encode:

- 12,283
- 25
- 92
- 144
If your client is requesting the data in JSON format, then it's probably best to take the results from your database call and convert them to a JSON-formatted string before returning it to your client.
But your client's AJAX call could also be requesting the data in XML format, too.
So the answer depends on what the client is expecting.

- 28,421
- 8
- 67
- 102