Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CakePHP 3: Ajax response is returning a 200 response code and a parsererror

I'm attempting to send an ajax request from a javascript file to a cakephp controller. The ajax is sending a simple json object (I've hardcoded it in this example for simplicity).

When I do logging, the server is able to decode the json string into an object. The $this->Votes->delete function is called successfully. My problem is that everything works as it should, except I'm still getting an error message anyways.

Below is my code, and below that is the output that I get from it.

Javascript:

function unvote() {
    $.ajax({
        type: 'POST',
        url: '../votes/unvote',
        async: false,
        contentType: 'application/json',
        dataType: 'json',
        data: JSON.stringify({'post_id':1}),
        success: function(data, textStatus, jqXHR){
            console.log(data);
            console.log(textStatus);
            console.log(jqXHR);
        }.
        error: function(jqXHR, textStatus, errorThrown){
            // this block gets triggered with a 200 response
            console.log(jqXHR);
            console.log(textStatus);
            console.log(errorThrown);
        },
    });
}

PHP: Votes Controller

public function unvote(){
    $this->autoRender = false;
    $vote = $this->Votes->newEntity();
    if ( $this->request->is('ajax') ) {
        $data = $this->request->input('json_decode');
        $vote = // get the correct vote from the database and save into this object
        if ( $this->Votes->delete($vote) ) {
            $this->response->body('Success');
            $this->response->statusCode(200);
        } else {
            $this->response->body('Failure');
            $this->response->statusCode(500);
        }
    }
    $this->response->type('json');
    return $this->response;
}

ajax Response:

Object{ readyState=4, responseText="", status=200, statusText="Ok", more...}
parsererror
SyntaxError:JSON.parse: unexpected end of data at line 1 column 1 of the JSON data
> return window.JSON.parse( data + "" );
like image 459
Brady Pacha Avatar asked Jan 12 '17 16:01

Brady Pacha


1 Answers

jQuery ajax function is expecting a json object and you aren't giving it json

Here are some suggestions for working with ajax in cakephp

  • I wouldn't set autorender to false. Instead create an ajax layout.
  • You need to set the _serialize view variable if you want to return data

I would suggest doing something like this.

$responseData = ['success' => true];
$this->set('responseData', $responseData);
$this->set('_serialize', ['responseData']);

Obligatory references from the docs

JSON and XML Data Views

There are two ways you can generate data views. The first is by using the _serialize key, and the second is by creating normal template files

Using Data Views

The _serialize key is a special view variable that indicates which other view variable(s) should be serialized when using a data view.

like image 76
styks Avatar answered Nov 03 '22 11:11

styks