Love Fuel?    Donate

FuelPHP Forums

Ask your question about FuelPHP in the appropriate forum, or help others by answering their questions.
Tutorial for using rest controller
  • Is there any good tutorial for rest controller? I dont have any idea using it. I also want to know how and where to use it? Is it used for ajax calls or any other things. any help will be appreciated
  • Have you seen this page? http://fuelphp.com/docs/general/controllers/rest.html
    class Controller_Test extends Controller_Rest {
    
        public function get_list()
        {
            $this->response(array(
                'foo' => Input::get('foo'),
                'baz' => array(
                    1, 50, 219
                ),
                'empty' => null
            ));
        }
    }
    
    http://localhost/test/list.json?foo=bar
    
  • Yes i have seen the page . I didnt have how to use it with ajax calls. having a big trouble in using when try to do ajax calls.
  • Samit Rimal wrote on Tuesday 8th of November 2011:
    Yes i have seen the page . I didnt have how to use it with ajax calls. having a big trouble in using when try to do ajax calls.

    There's a tutorial about ajax login http://saaboke.com/?p=257 hope this helps.
  • Thanks huzzi , it worked the output is in array but i need the output in json format.I followed the instruction as per link and set the default format from xml to json but still it outputs in array. i want to output it in json i have used set_header to json in rest controller
    here is my controller
    class Controller_Test extends \Controller_Rest
    {
        function get_testone()
        {
         
            $this->response->set_header('Content-Type','application/json');
           return $this->response(array('hello'=>'this is json and it is sucessfull'));
        }
     }
    
    OUtput :
    array ( 'hello' => 'this is json and it is sucessfull', )
    i need the output:
    {"hello":"this is json and it is sucessfull"}
    
  • try removing $this->response->set_header('Content-Type','application/json'); I'll try to post some code for you tonight from my project.
  • no luck though i tried removing set_header from the script. I dont understand wht is wrong
  • That probably means format detection doesn't work, hasn't been set or passed properly in the request, or is misconfigured. You don't mention which FuelPHP version you are using. For 1.1, see http://fuelphp.com/dev-docs/general/controllers/rest.html. You'll see that it detects the format used based on the extension of the request (in the example list.json). If you don't have a format like that, you need to either configure the default format in the rest.php config file (by default it is xml), or the $this->rest_format property of your rest controller.
  • Hi WW i am using 1.1 .
    here is my source code
    modules/chat/controller/test.php
    <?php
    namespace Chat;
    /* 
     * To change this template, choose Tools | Templates
     * and open the template in the editor.
     */
    class Controller_Test extends \Controller_Rest
    &#123;
        function get_testone()
        &#123;
        
            $this->rest_format='json';
           $this->response(array('hello'=>'this is json and it is sucessfull'));
        }
         function post_test()
        &#123;
          $this->rest_format='json';
            $this->response(array('hello'=>'this is a post method'));
        }
    }
    ?>
    
    filename:modules/chat/views/chat.php
    <div id="test1"></div>
    [removed]
        var hostname=[removed].pathname;
        //alert&#40;hostname&#41;;
        $(document).ready(function()&#123;
            $("#test").click(function()&#123;
                //alert&#40;'hello'&#41;;
                $.ajax(&#123;
                     data:&#123;samit:'rimal'},
                     url:hostname+"/test/testone.php",
                    //when i use /test/testone.json  no result is shown in the browser
                     type:"GET",
                      cache: false,
                     
                     success :function(data)&#123;
                        
                       $('#test1').html(data)
                     },
                      error: function(XMLHttpRequest, textStatus, errorThrown)
                        &#123;
                            $('#test1').html(errorThrown);
                            
                        }
    
                });
            
            });
        });
    [removed]
    
    i would like to know if the ajax calls can be done without using rest controller also or not to output in json format. if that would be possible i would use it temporarily ,any answers will be appreciated
    regards,
  • FuelPHP only outputs what you put in the response. So it's not a problem for a standard controller method to return json, the only difference is that you'll have to hard-code ajax detection, json encoding/decoding, http headers, etc. This is what the Rest Controller does for you in the background.
  • Thank U WW for help . when tried by typing the path of rest controller then i got the result in json but it is not showing when im calling it through ajax, the code i posted above.Is there something i missed?
  • This is how i have it working
    controller/ajax.php
    <?php
    class Controller_Ajax extends Controller_Rest &#123;
    
        public function post_search() &#123;
    
            $search = \Input::post("term") . "%";
            $result = DB::select()->from('customers')->where_open()
                            ->where('firstname', 'like', $search )
                            ->where_close()
                            ->or_where_open()
                            ->where('postcode', 'like', $search )
                            ->or_where('telephone', 'like', $search 
    
    )
                            ->or_where_close()->execute();
    
            $data['response'] = 'true';
            $data['message'] = array();
            foreach ($result as $row) &#123;
                $data['message'][] = array('label' => $row['firstname'],
                    'value' => $row['firstname'],
                    'details' => $row);
            }
            $this->response($data);
        }
    }
    

    view
    <.Script type="text/javascript">
        jQuery(document).ready(function($) &#123;
            $(function() &#123;
                $("#query").autocomplete(&#123;
                    minLength: 2,
                    source: function(req, add)
                    &#123;
                        $.ajax(&#123;
                            url: '/ajax/search.json',
                            dataType: 'json',
                            type: 'POST',
                            data: req,
                            success:
                                function(data)
                            &#123;
                                if(data.response =='true')
                                &#123;
                                    add(data.message);
                                }
                            }
                        });
                    },
                    select: function(event, ui) &#123;
                        var data = ui.item.details;
                        $('#query').val(ui.item.label);
                        $("#title").val(data.title);
                        $("#firstname").val(data.firstname);
                        $("#lastname").val(data.lastname);
                        $("#address1").val(data.address1);
                        $("#address2").val(data.address2);
                        $("#town").val(data.town);
                        $("#county").val(data.county);
                        $("#postcode").val(data.postcode);
                        $("#telephone").val(data.telephone);
                        $("#mobile").val(data.mobile);
                        $("#email").val(data.address1);
                        $("#nationality_id").val(data.nationality_id);
                        $("#dob").val(data.dob);
                        $("#identity_id").val(data.identity_id);
                        $("#notes").val(data.notes); 
                    }
                });
            });
    
        });
    <.Script>
    

  • Thank u Huzzi , it helped me.
  • The default format issue still does not appear to be fixed in 1.4. In my case the default format is php (even though I've set it to json in the rest config) and apart from the results, the executed query is also being exposed in the obj props -- great security issue imo
  • I can't comment on that without knowing what you exactly do, so show your controller code please, and tell us how you call it.

    The REST controller returns the format in the type configured, or in the type requested. The default format is XML, not PHP. You will get a PHP array if no format is set or detected, and you request your method through a browser instead of via an AJAX call, since that's the only way an array can be displayed in HTML.
  • return array(

    /*
    | What format should the data be returned in by default?
    |
    | Default: xml
    |
    */
    'default_format' => 'json',


    This is inside app/config/rest.php

    class Controller_Api_1_User extends Controller_Rest

    {
    public function before()
    {
    parent::before();
    if ( ! \Gm::gm_verify_credentials())
    {
    return $this -> response(array('errors' => 'Unauthorized request.', ), 403);
    }
    }

    public function after($response)
    {
    return $response;
    }

    public function get_user_profile()
    {
    $user = \Gm::gm_profile_info($this->param('screen_name')); //Retrieve a user model
    return $this->response(array(
    'user' => $user
    ), 200);
    }
    }


    Yes, you're right the default format is XML when you don't specify the dataType in an $.ajax call. This returns json perfectly

      self.screen_name.subscribe(function(newScreenName) {
    self.user([]);
    self.pending_request(true);
    $.ajax({
    url : self.base_api() + 'get/user/' + newScreenName,
    type: 'GET',
    dataType : 'json',
    success : function(d) {
    if (d.user)
    {
    self.user(new ProfileUser(d.user));
    }
    },
    error : function(d) {
    }
    }).done(function() {
    self.pending_request(false);
    });
    }.bind(self));


    But if you do not specify the format (by either adding dataType: 'json' or appending .json to the url), it returns XML. If you just call the API method in a browser, the entire object is being returned in a php format. Any way to at least prevent the exposure of the executed query in the response object in this type of case?
  • Just add 

    'ignore_http_accept' = true,

    in your rest.php config file.

    I assume you did not define explicitely the accept header, so its value starts with 'text/html'. The Controller uses this value and the result it returns is the full PHP description of your object.
  • Worked like a charm! Thanks so much, Pascal! :)
  • You're welcome :)
    IMHO, the documentation is a bit misleading about this point. Maybe we should improve it. I'll try to suggest something.
  • default_format is only used when no format could be determined. And since on of the checks is using the HTTP_ACCEPT header, a format can virtually always be determined.

    Either use the ".json" extension, "?format=json" on the URL, or the $format property to define the format.
  • Harro, the doc says: 
    • use the protected property $format if it contains a supported format 
    • use the URL extension if it is a supported format 
    • use the format specified by the :format variable in the route if it contains a supported format 
    • use the default value defined by the $rest_format property of your class
    But if you define $rest_format without ignore_http_accept=true, it just does not work. You get PHP in your response, instead of the format you defined in $rest_format.
    So, either the documentation should mention this, or the behavior of _detect_format is incorrect. Another solution could be to change the default value for ignore_http_accept.
  • I've looked into the code history, but HTTP_ACCEPT processing has been in there from day one. So it's indeed strange that it isn't documented. According to the code, the sequence mentioned in the docs is also wrong.

    I'll correct that.

    edit: just done that.
  • The HTTP_ACCEPT will be "*/*" when using Ajax call without specific a dataType. And this will always match the first support_format which is xml in function detect_format.

    Is it possible that retrieve the default_format when HTTP_ACCEPT is "*/*" ?
  • Good suggestion.

    There is no such thing as a "default_format", but there is a "rest_format" property which is used if no valid accepted language is found, so I've updated the Controller_Rest to use that.

Howdy, Stranger!

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

In this Discussion