Question

I am new to the world of Kohana/php and am having some issues understanding how to get the result of an ajax request. This request is being called from a click action and is invoking the following method.

function addClickHandlerAjax(marker, l){
  google.maps.event.addListener(marker, "click",function(){
    console.log(l.facilityId);
     removeInfoWindow();
     //get content via ajax
      $.ajax({
      url: 'map/getInfoWindow',
      type: 'get',
      data: {'facilityID': l.facilityId },
      success: function(data, status) {
        if(data == "ok") {
          console.log('ok');
        }
      },
      error: function(xhr, desc, err) {
        console.log(xhr);
        console.log("Details: " + desc + "\nError:" + err);
      }
    }); // end ajax call

});
}

Inside of my controller I have a method

       public function action_getInfoWindow(){

      if ($this->request->current()->method() === HTTP_Request::GET) {

        $data = array(
            'facility' => 'derp',
        );

        // JSON response
        $this->auto_render = false;
        $this->request->response = json_encode($data);

    }
  }

I see an HTTP request in fiddler and it passed the correct facilityID parameter. However I am having some disconnect about how to connect all the pieces together.

Was it helpful?

Solution

To send a response to the browser, you should user Controller::response instead of Controller::request::response. So your code should look like this:

public function action_getInfoWindow() {
    // retrieve data
    $this->response->body(json_encode($data));
}

That should give you some output.

Checkout the Documentation for more detailed info.

Edit

What you could do, to make your life a bit easier, especially if you gonna use ajax requests a lot, is to create an Ajax controller. You can stuff all checks and transforms in it, and never worry about it anymore. An example controller could look like below. Also checkout the Controller_Template which is shipped as an example by Kohana.

class Controller_Ajax extends Controller {
    function before() {
        if( ! $this->request->is_ajax() ) {
            throw Kohana_Exception::factory(500, 'Expecting an Ajax request');
        }
    }

    private $_content;

    function content($content = null) {
        if( is_null( $content ) ) {
            return $this->_content;
        }
        $this->_content = $content;
    }

    function after() {
        $this->response->body( json_encode( $this->_content ) );
    }
}

// example usage
class Controller_Home extends Controller_Ajax {
    public function action_getInfoWindow() {
        // retrieve the data
        $this->content( $data );
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top