Search code examples
jqueryajaxcakephpinternal-server-error

500 internal server error when sending data to controller and try to make an API call


I'm trying to make a $.ajax call and send some data to a controller in cakephp and make an API call, I keep getting 500 internal server error.

jquery file

$.ajax({
type: 'POST',
url: '/src/Controller/PagesController/createLinks',
data: {
    spotifyLink: spotifyLink,
    accessToken: access_token,
    boardID: boardID,
},
dataType: 'json',
complete: function (response) {
    console.log("data coming back from pagesController.php" + response.responseText);
},
error: function (jqXHR, textStatus, errorThrown) {
    console.log(jqXHR, textStatus, errorThrown);
}
});

controller file

public function createLinks() {

    if ($this->request->is('ajax') && $this->request->is('post') ){

        $link = $_POST['spotifyLink'];
        $token = $_POST['access_token'];
        $boardID = $_POST['boardID'];

        $apiLink = 'https://api.linkfire.com/campaigns/boards/'.$boardID.'/links';

        $body = array("baseUrl" => $link);

        $http = new Client();
        $response = $http->post($apiLink, $body,
            ['headers' =>['Authorization' => 'Bearer '.$token, 
                          'content-type' => 'application/json']]);
        $json = $response->json;
        echo ($body);
        return $response;
    }

in my Router file I have

$routes->connect('/src/Controller/PagesController/createLinks', ['controller' => 'Pages', 'action' => 'createLinks']);

and this is the error I'm getting

jquery-3.3.1.min.js:2 POST http://localhost:8765/src/Controller/PagesController/createLinks 500 (Internal Server Error)

please note that the data gets printed in the console and in the response body I have the following

{"message":"An Internal Error Has Occurred.","url":"\/src\/Controller\/PagesController\/createLinks","code":500}

log file shows the following error:

Error: [Cake\Routing\Exception\MissingControllerException] Controller class Js could not be found.

Request URL: /js/MDB/js/bootstrap.min.js.map

2018-07-12 07:23:17 Error: [LogicException] Controller actions can only return Cake\Http\Response or null.

Request URL: /src/Controller/PagesController/createLinks Referer URL: http://localhost:8765/

any help would be very much appreciated.


Solution

  • The url in the ajax call "/src/Controller/PagesController/createLinks" should be "pages/create-links".

    Also, have a look at json views: https://book.cakephp.org/3.0/en/views/json-and-xml-views.html