Love Fuel?    Donate

FuelPHP Forums

Ask your question about FuelPHP in the appropriate forum, or help others by answering their questions.
AJAX response in Controller_Template
  • I have tried a few ways, and it seems I haven't found a way to output a JSON string from a Controller extended from Controller_Template. I'm trying to make a form which is AJAX based, but if JavaScript isn't working it degrades to the form page.
  • You can disable the template auto rendering by setting the value of $auto_render to false in your action function. Example: <?php class Controller_Test extends \Controller_Template { public function action_form() { // ... if($ajax_detected) {
    $this->auto_render = false;
    echo json_encode( /* ... */ );
    } // ... }
    }
  • Thanks Sebastien, also is it safe to echo from the controller ? or would a $this->response(); work like with the REST controller ?
  • Forget the echo, it was ugly and I did this example very fast. This is better: $this->response->body = json_encode(array('plop')); The $this->response() function is not available because your controller extends Controller_Template and this function is only provided by Controller_Rest.
  • I know this post is a little dated, but for anyone browsing for similar issues, you can use:
    // data array containing the info you want to convert to json
    $data = array(
        'field1' = 'data1',
        'field2' = 'data2'
    );
    
    $this->response->body = \Format::factory($data)->to_json();
    

    Take a look at the Format Class Docs... http://fuelphp.com/docs/classes/format.html there are several other helpful items of interest in there.
  • I didn't see this mentioned, so it's worth saying. There is an "is_ajax" method within the Input class, so if($ajax_detected) might be improved as... if(Input::is_ajax) Maybe you already knew about this, but if not I wanted to give a heads up as I went through creating my own ajax checks for a few projects before I realized this method existed.

Howdy, Stranger!

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

In this Discussion