1

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

Iyad Al aqel
  • 2,020
  • 3
  • 21
  • 32

3 Answers3

2

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

Community
  • 1
  • 1
Chris Laplante
  • 29,338
  • 17
  • 103
  • 134
1

You don't have to use JSON but you can encode any associative array using the function json_encode:

http://php.net/manual/en/function.json-encode.php

Doug Molineux
  • 12,283
  • 25
  • 92
  • 144
0

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.

David Hoerster
  • 28,421
  • 8
  • 67
  • 102