4

I want to know when will it be reasonable to pull data from a php page via ajax in form of json array.. Suppose I have this code :

$.ajax({ type: "get", url: "assets/update_cart_user_fstore.php", data: up, cache: false, success: function(r){ $(#item).html(r); }, }); 

and in PHP page I am echoing a variable

$hello = "I am code!"; echo $hello; 

And with JSON

$.ajax({ type: "get", url: "assets/update_cart_user_fstore.php", data: up, cache: false, success: function(r){ var obj = jQuery.parseJSON(r); $('#item').html(obj.code); }, }); 

and in PHP I'm echoing the JSON array

$hello = "I am code!"; $response = array(); $response['code'] = $hello; echo json_encode($response); 

Now I know that in case of echoing more than 1 variable JSON is appropriate...But is it necessary here? And am I using JSON properly..?

Please explain..

2
  • It wont make sense for this scenario, however if you need to update several places on UI and if you do OO code, it perfectly useful and easy to you AJAX with JSON. Commented Mar 4, 2014 at 7:59
  • JSON is usefull if you want to transmit objects, arrays,... but with a small data weight (VS xml, xml is bigger to transmit). If you only return a simple string, JSON is not necessary. But it depend of the developer and its habits... Commented Mar 4, 2014 at 8:01

1 Answer 1

2

Is it necessary in this case? No, it isn't.

But using JSON has some advantages, for example

  • Your data has a strict, standardized structure. This means, less chance for errors.
  • You can scale it better.
  • You can debug it easier. For example, Tools like Firebug support JSON

Two good articles, which will go into more detail:

  1. http://www.revillweb.com/articles/why-use-json/
  2. http://blog.programmableweb.com/2013/11/07/xml-vs-json-a-primer/

I've rarely found a use case where I wouldn't prefer JSON.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.