Question

I am using get() method in data mapper to select columns from database. I am passing this object to json_encode(); When I do this, I get this error

json_encode()  type is unsupported, encoded as null

Update three

["{\"id\":1,\"name\":\"JOHN\",\"city\":\"null\"}"
,"{\"id\":2,\"name\":\"MICHEAL\,\"city\":\"null\"}"]

This is my response, I do not select city but still city appears. How to get json in correct format

SyntaxError: JSON.parse: unexpected non-whitespace character after JSON data

[Break On This Error]   

var jsonData = JSON.parse(data);
Was it helpful?

Solution

Encoding a Datamapper object to a json object requires a function from an extension. You can find ways to import extensions here: http://datamapper.wanwizard.eu/pages/extensions.html This is one way of doing it:

class Test extends DataMapper {

    // Include the json extension
    var $extensions = array('json');
.......

  $test= new Test();                
  $test->where('id', $this->input->post('id'));
  $test->select('id,name');
  $test->get();
  $test->set_json_content_type();
  echo $test->all_to_json();

The fact that the 'city' column is there is normal. From the DataMapper user guide:

The object is populated with all objects from its corresponding table, but with only the title and description fields populated

To decode your JSON, you need to use this method (don't forget to import the extension if you haven't already)

$n = new Test();
$n->from_json([put your JSON string here]);

OTHER TIPS

I haven't used Datamapper for CI, but I'm pretty sure you should be doing the following:

$test= new Test();                
$test->select('id,tag_name');
$test->where('id', $this->input->post('id'));
$test->get();
json_encode($test);

Note: calling ->get() should be last call, before you use the $test variable to JSON encode it.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top