0

i'm using phonegap in order to make an application, then i'm using CodeIgniter as an API. To get the data, i'm using a simple $.post from jQuery to a REST URL in CodeIgniter.

$.post(DIR+trad+"/format/json", function(data){
    traducciones = jQuery.parseJSON(data);
}, json);

Based upon this, i got 2 questions, because i don't know if i should do it in different post methods.

The first question is, how do i get the data in json format? The second question is, is there any way to call the json object directly from my view (HTML) ? or i need to do it using jquery or javascript?

maxwellnewage
  • 355
  • 2
  • 13

2 Answers2

1

how do i get the data in json format?

Searching for codeigniter+json gives me Output Class which has this example:

$this->output
    ->set_content_type('application/json')
    ->set_output(json_encode(array('foo' => 'bar')));

is there any way to call the json object directly from my view (HTML)?

Generally speaking, if you are generating the JSON yourself and you want to use it in HTML, then you will just skip generating JSON and use the data directly.

Generating JSON from a view only really becomes useful if you want to make the raw data available over a network.

If you want to fetch the data over HTTP for your view, then that is a job for the Model. See How to send a GET request from PHP?. This is useful if you have two different applications. One providing a web service for the data and one providing the user facing application.

If you want to update the page with new data after it has loaded, then this is a good usecase for JSON, but you can only do that with JavaScript (or another client side programming language).

Community
  • 1
  • 1
Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
  • i need json because is the response of the module REST in CI. I can create multiples divs and assign: $("#div").html(data.valuejson); but i have too elements for insert on the HTML – maxwellnewage May 14 '13 at 16:34
1

If you want to using JSON as response format, just do like

$.post(url, {
    "dataType" : "json",
    "success" : function(response) {
         // process your response here, it will be treated as JSON object
    }
});
Francis.TM
  • 1,761
  • 1
  • 18
  • 19