0

I'm making a $.ajax post call to a controller on cakephp to send some data to the controller and then use that data to connect to a 3rd party API and create a link, the $.ajax call works as expected and I get the post data however there's a problem with call to the 3rd party API,

public function createLinks() {

    if ($this->request->is('ajax') ) {
        $this->autoRender = false;
    }
    if ($this->request->isPost()) {
        $link = $this->request->data['spotifyLink'];
        $token = $this->request->data['accessToken'];
        $boardID = $this->request->data['boardID'];
        $trackTitle = $this->request->data['trackTitle'];
    }
    $apiLink = 'https://api.linkfire.com/campaigns/boards/'.$boardID.'/links';
    $body = array("track" => $trackTitle,"baseUrl" => $link);

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

this is what I'm getting back

{"readyState":4,"responseText":"{}","responseJSON":{},"status":200,"statusText":"OK"}

my question is can I receive the post data from ajax call and make the http->post call in the same function? Is there any error in the above code because the $http->post call doesnt seem to work, any help would be appreciated.

if I change echo json_encode($response); to return $response; I get the 500 internal server error and in the log file it says

Controller actions can only return Cake\Http\Response or null
akano1
  • 40,596
  • 19
  • 54
  • 67
  • 1
    **[Controllers should _never_ echo data](https://stackoverflow.com/a/42379581/1392379)**! – ndm Jul 12 '18 at 11:08
  • Hi, thanks for the reply, If I return $reponse; I get the controller actions can only return Cake\Http\Response or Null error, do you know how I can make the 3rd party api call? – akano1 Jul 12 '18 at 11:11
  • Please read the answer and the linked docs carefully, your `$response` variable is not the same as the response object mentioned there. – ndm Jul 12 '18 at 11:15
  • after reading the docs I change the last line of code to $this->response = $this->response->withType('json'); return $this->response; now I'm getting "parsererror" SyntaxError: Unexpected end of JSON input, do you know what's wrong? – akano1 Jul 12 '18 at 12:18
  • Most likely your response body content is empty of malformed. – ndm Jul 13 '18 at 13:04

0 Answers0