Phalcon Javascript Issue

In Phalcon when I calling the ajax call then it is returning the complete html page instead of response.

When I am clicking on the image I am calling the javascript function. In that function I am having the below ajax call. But the saveEventIdAction is not calling.

Please help me on this.

ex: $.ajax({ type: "POST", url: "index/saveEventId/", crossDomain: true, dataType: "json", data: { event_id: eventId, event_name: eventName} , success: function(response) {}});

edited Dec '17

Phalcon will respond with what you code it to respond with.

class IndexController extends PhController
{
    function saveEventIdAction() {
        if($this->request->isPost()) {
            $data = $this->request->getPost();
            // app logic
            return $this->response->setJsonContent(['some'=>'response data'])->send();
        }
    }
}

I tried the same example you gave but I am getting the index page html code is returning instead of response we sent from saveEventIdAction

Phalcon will respond with what you code it to respond with.

class IndexController extends PhController
{
  function saveEventIdAction() {
      if($this->request->isPost()) {
          $data = $this->request->getPost();
          // app logic
          return $this->response->setJsonContent(['some'=>'response data'])->send();
      }
  }
}
edited Dec '17

Are we need ->send(); ? Or just without it.

return $this->response->setJsonContent(['some'=>'response data']);


73.5k
edited Dec '17

here is an old code of mine that i am using everywhere for ajax calls


<?php

namespace Whatever\api\Controllers;

use Phalcon\Mvc\Controller;

/**
 * Class UsersController
 *
 * @package Api\Controller
 */
class BaseController extends Controller
{

    protected $translationService;

    public function onConstruct() {

        $this->translationService = $this->getDI()->getShared("getTranslationMessages");
    }

    public function translate($name) {
        return $this->translationService->query($name);
    }
    /**
     * allows only ajax calls
     *
     * @param bool $onlyGet
     * @param bool $token
     * @param bool $soft
     */

    public function onlyAjax($onlyGet = false, $token = false, $soft = false)
    {

        if ($this->request->isAjax() == false) {
            return $this->handleAjaxError($soft);
        }

        if ($onlyGet === true) {
            if ($this->request->isGet() === false) {
                return $this->handleAjaxError($soft);
            }
        }

        if ($token && $this->security->checkToken() == false) {
            return $this->handleAjaxError($soft);
        }
    }

    public function handleAjaxError($soft = false)
    {

        if ($soft === false) {
            $this->response->setStatusCode(404, 'Not found');
            $this->response->redirect("/404");
        }

        $this->response->setJsonContent(
            array(
            'success' => false,
            'url' => $this->request->getURI(),
            'parameters' => $this->dispatcher->getParams()
            )
        );
    }

    public function afterExecuteRoute(\Phalcon\Mvc\Dispatcher $dispatcher)
    {

        if ($this->request->isAjax() == true) {

            $this->response->setContentType('application/json', 'UTF-8');
            $data = $this->view->getParamsToView();

            $json = [];

            if (isset($data['error']) && $data['error'] !== 0 && $data['error'] !== true) {
                $json['success'] = false;
                $json['message'] = $data['error'];
            } else {
                $json['success'] = true;
                if (isset($data['message'])) {
                    $json['message'] = $data['message'];
                }
                if (isset($data['results'])) {
                    $json['results'] = $data['results'];
                }

            }

            $this->response->setJsonContent($json);
        }
    }

    public function onlyLoggedUsers()
    {
        if ($this->getDI()->getShared("auth")->isUserSignedIn() === false) {

            http_response_code(401); //unauthorized

            echo json_encode(
                [
                'success' => false
                ]
            );
            exit;

        }
    }

}

and then for actually stuff


<?php

namespace Whatever\api\Controllers;

use Helpers\Uploads\HandleUpload;

class UploadsController extends BaseController {

    public function AvatarAction(){

        $this->onlyAjax();
        $this->onlyLoggedUsers();

        $this->view->error = 0;

        $user_id = $this->auth->getUserId();

        $uploadAdapter = new \whatever\Plugins\Uploads\Adapter\UserAvatar($user_id, [
                "watermark" => false,
                "trim" => true
            ]
        );

        $handleUpload = new HandleUpload($uploadAdapter);

        $errors = $handleUpload->errors;

        if (count($errors) > 0){
            $this->view->error = $errors[0];
            return false;
        }

        $result = [];

        $result['success'] = true;
        $this->view->results = $result;
        return false;
    }
}

Ahh.. but routes will be transformed to kebab case!

Use this url: index/save-event-id instead of index/saveEventId

My guess is your ajax call is to the wrong URL. Do you have an .htaccess rule that redirects 404 requests to your index page? If so, then likely you're not requesting the correct url.



2.9k

Maybe you need to disable the view

$this->view->disable();

setJsonContent in your response

$response = new \Phalcon\Http\Response();
$response->setJsonContent([...]);

and return $response

return $response;

That worked well for me