Magento – Handling AJAX requests

ajaxcontrollershttp-requestjavascript

I have a class in my custom module that needs to handle various AJAX requests as well as a typical Magento request. I am using AngularJS on the front end.

Angular will submit request parameters in JSON format, so if you have a simple call such as:

$http.post('/mymodule/mycontroller/myaction', {param1: 'foo', param2: 'bar'});

You cannot simply use $this->getRequest()->getParams() to get param values. Instead you need to use file_get_contents(php://input) to get the raw input string which you can then json_decode or do whatever you need to to access the request params.

See: https://stackoverflow.com/questions/15707431/http-post-using-angular-js

As I said, my custom class needs to handle both AJAX requests from Angular as well as normal Magento requests (or even AJAX requests from jQuery). The problem is handling the parameters in a consistent fashion.

How can I normalize the request from Angular so that Magento still has access to $this->getRequest()->getParams()?

Best Answer

Use one action controller that has split functionality. Have your ajax request pass something like '&ajax=1' as a parameter. If this parameter exists then offer one functionality. If this parameter isn't set then offer the second.

public function controllerAction(){
    $jsonContents = file_get_contents(php://input);
    if(!jsonContents){
       $jsonContents = $this->getRequest()->getParams();
    }
    $contents = json_decode($jsonContents);
    if($contents['isAjax']==1){
        $response = $this->ajaxRequest();
    }else{
        $response = $this->normalRequest();
    }
}

protected function ajaxRequest(){
    ....
    //return response;
}

protected function normalRequest(){
    ....
    //return redirect (or whatever);
}

Nice and simple.

Related Topic