1

On Concrete5-8.1.0 I have created a custom block with Ajax functionality based largely on the concrete5 docs - Implementing Ajax in Block View Templates. However, unlike the example I do not want to reload the block view, I want to pass specific messages based on the input. I tried a simple echo '{"msg":"ok"}'; and return '{"msg":"ok"}); as a test, but requests to the function yielded an empty response.

I found How To Send JSON Responses with Concrete5.7 and used Option 2 (for greater control of error codes) resulting in the following test code:

public function action_submit($token = false, $bID = false) {

  if ($this->bID != $bID) {
    return false;
  }
  if (Core::make('token')->validate('get_paper', $token)) {

    //save to database
    //removed for brevity

    //send email
    if ($this->emailto != '') {
      //removed for brevity
    }

    if ($_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest') {
      return new Response(
        json_encode(array('msg' => 'ok')),
        200,
        ['Content-Type' => 'application/json']
      );
    } else {
      Redirect::page($page)->send();
    }
  }
  else {
    return false;
  }
  exit;
}

The database save and email function as expected, but the response is still empty. In Chrome Dev Tools, I see the correct Content-Type (as a test, I tried text/html and saw that change in dev tools), but no content. Interestingly, if I change the status from 200 to 500 I not only see the status change reflected in dev tools, I also see the {"msg":"ok"} content that I'm expecting, but changing the status back to 200 and the content is again empty.

It seems I'm missing something simple... I have verified that all caching is turned off within C5 (site is still in development), I have also verified the jQuery request includes cache:false, but the solution escapes me.

thadmiller
  • 539
  • 1
  • 4
  • 19

0 Answers0