0

I am having problem sending PUT and DELETE REST API from my front end to my ZF2 backend. However: I am able to send POST and GET request and it's working fine but not PUT and DELETE won't. Why?

Below is my ajax code:

 $.ajax({
        type: "PUT",
        dataType: "json",
        data: data,
        url: "/backend/api/product",
        statusCode: {
            200: function (data) {
                product= data.content;
            }
        }, error: function (data) {
            alert(data.responseJSON.message);
        }
    });

The error that I get from my ZF2 are:

Zend\View\Renderer\PhpRenderer::render: Unable to render template "api/product/replace-list"; resolver could not resolve to a file

1
  • The error you're getting is because ZF2 can't find the view for api/product/replace-list which I feel is unrelated to the question you're asking. Please show what your controller action looks like and possibly your view_manager config. Commented May 20, 2015 at 8:41

1 Answer 1

1

Make sure you are using restful controller with JsonModel. The restful controller will handle the restful requests PUT and DELETE. And the JsonModel will produce JSON output.

Here is a sample code that may help you,

use Zend\ViewModel\JsonModel;
use Zend\Mvc\Controller\AbstractRestfulController;

class ProductController extends AbstractRestfulController
{    
    public function delete($id){

        // to handle delete 
        $responseData = new JsonModel(array(
            'key' => 'value'            
        ));

        return $responseData ;
    }

    public function update($id, $data){

        // to handle update
        $responseData = new JsonModel(array(
            'key' => 'value'            
        ));

        return $responseData ;
    }
}

Also in restful PUT method requires two params

  1. ID (includes in url)
  2. DATA (array)

so modify your ajax call as

$.ajax({
    type: "PUT",
    dataType: "json",
    data: data,
    url: "/backend/api/product/"+id,
    statusCode: {
        200: function (data) {
            product= data.content;
        }
    }, error: function (data) {
        alert(data.responseJSON.message);
    }
});
Sign up to request clarification or add additional context in comments.

1 Comment

adding the "id" at the back of the ajax call url do the magic =) Thanks! You saved lot of my time!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.