CakePHP 3: Ajax response returns 200 response code and parsererror

I am trying to send an ajax request from a javascript file to a cakephp controller. Ajax sends a simple json object (for simplicity, I hard-coded it in this example).

When I log the server, the server can decode the json string into an object. The function $this->Votes->deleteis called successfully. My problem is that everything works as it should, but I still get the error message.

Below is my code, and below is the result 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: Voice 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 + "" );
+6
source share
1 answer

jQuery ajax json, json

ajax cakephp

  • autorender false. ajax.
  • _serialize,

- .

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

JSON XML

. - _serialize, -

_serialize , , .

+2

Source: https://habr.com/ru/post/1014019/


All Articles