Love Fuel?    Donate

FuelPHP Forums

Ask your question about FuelPHP in the appropriate forum, or help others by answering their questions.
Pass a model result as array from controller to view via Ajax
  • Hi,
    I'm trying to send an array encoded as json from a controller to view.

    In my controller (server side):

    $users = Model_Users::find(1);
    $a=$users->to_array();
    return json_encode($a);


    In my view:

    $(document).ready(function() {  
    $.ajax({
    url: 'my/url...',
                    method: 'POST',
                    data: {},
                    success: function(data) { 
                        alert(data); 
                    }
            });  
    });

    This working fine, infact in the view I get this alert: 

    data = {"name":"Jhon","surname":"Larry","age":"25"}

    This work because the result of the query is only one row.

    Instead when I try to get more than one query result, example:

    $users = Model_Users::find('all');
    $a=array();
    foreach ($users as $user){
    array_push($a,$user->to_array());
    }
    return json_encode($a);

    In this case an empty response comes up, in fact I get this alert: 

    data = []

    What is the problem?
    Thanks in advance
  • HarroHarro
    Accepted Answer
    Normally, you would not mix REST and non-REST functions in the same controller, but you would have specific controllers for your REST API, which extend Controller_Rest instead of Controller.

    Output handing of standard controllers isn't designed to return raw json.

    And you can also use the format class to convert to json, no need to do that manually.
  • Thanks for your answer Harro, I do that because in this way I can reuse most of the code already written in the controllers, otherwise I must duplicate my controllers in REST controllers that would do the same things...It's right?
  • HarroHarro
    Accepted Answer
    I'm not stopping you, I'm only highlighting best practice. Fuel doesn't care. The only thing you have to look out for is that it outputs exactly what you think it does.

    As to why you don't get your json returned, I don't know. You'll have to debug.
  • Ok I get it! thanks...I tried to print my output before I send it:

    This is the result of the first json_encode($a),when the model return one row: (It works)
    {"id":"1","name":"Jhon","surname":"Larry","age":"25"}

    This is the result of the second json_encode($a),when the model return more than one row: (doesn't works)
    [{"id":"1","name":"Jhon","surname":"Larry","age":"25"},{"id":"4","name":"Matt","‌surname":"Damon","age":"38"}] 

    I don't know why I can't receive the second one in my view...I'm going to go mad!
  • HarroHarro
    Accepted Answer
    This is all very weird, since a { } means it's an object, not an array. It translates to:

    array (size=2)
      0 =>
        object(stdClass)[29]
          public 'id' => string '1' (length=1)
          public 'name' => string 'Jhon' (length=4)
          public 'surname' => string 'Larry' (length=5)
          public 'age' => string '25' (length=2)
      1 =>
        object(stdClass)[30]
          public 'id' => string '4' (length=1)
          public 'name' => string 'Matt' (length=4)
          public '‌surname' => string 'Damon' (length=5)
          public 'age' => string '38' (length=2)

    So what works is an object, what doesn't work is an array of objects. Which does not match your code example, somewhere something else happens, to_array() doesn't return objects...
  • I'm sorry, I haven't explained well...the result that I introduced to you, is referred to the json_encode($a)
    so is correct that the result is an object (specifically a JSON)...and is exactly what you said (what works is a json (object), what doesn't work is a json with more than one element)

    ...why? I still don't get the problem
  • HarroHarro
    Accepted Answer
    I don't know. It works fine here:

    public action_test()
    {
            $a = json_decode('[{"id":"1","name":"Jhon","surname":"Larry","age":"25"},{"id":"4","name":"Matt","‌surname":"Damon","age":"38"}]');
            var_dump($a);
            return json_encode($a);
    }

    displays that var_dump I already posted, and returns JSON without any problems (and exactly the same as the input).
  • Yes, in case you manually give an input, all works fine...but if you trying to give the input using the ORM Model, in this way:

    public action_test()
    {
    $users = Model_Users::find('all');
    $a=array();
    foreach ($users as $user){
    array_push($a,$user->to_array());
    }
    return json_encode($a);
    }

    the result will be an empty JSON, like this:
    data = []
  • HarroHarro
    Accepted Answer
    That exact code works fine here:

    // method

    public function action_json()
    {
        $o = Model_table4::find('all');
        $a = array();
        foreach ($o as $oo)
        {
            array_push($a,$oo->to_array());
        }
        var_dump($a);
        return json_encode($a);
    }

    // results

    array (size=4)
      0 =>
        array (size=3)
          'id' => int 1
          'name' => string 'Ned' (length=3)
          'position' => string 'kitchen' (length=7)
      1 =>
        array (size=3)
          'id' => int 2
          'name' => string 'Bob' (length=3)
          'position' => string 'changed again!' (length=14)
      2 =>
        array (size=3)
          'id' => int 3
          'name' => string 'Jon' (length=3)
          'position' => string 'server' (length=6)
      3 =>
        array (size=3)
          'id' => int 99
          'name' => string 'Fiets' (length=5)
          'position' => string 'changed!' (length=8)

    // JSON result

    [{"id":1,"name":"Ned","position":"kitchen"},{"id":2,"name":"Bob","position":"changed again!"},{"id":3,"name":"Jon","position":"server"},{"id":99,"name":"Fiets","position":"changed!"}]
  • you kill me!
    In the call of the model there is a damn where clause
    so my code is correct, your code is correct and the empty result was correct!!!!!
    I'm sorry for your wasted time...I apologize!
  • HarroHarro
    Accepted Answer
    lol. shit happens... ;-)

Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

In this Discussion