We have moved our forum to GitHub Discussions. For questions about Phalcon v3/v4/v5 you can visit here and for Phalcon v6 here.

Ajax Request Always Returning Error even on Success

Hey, I've got a simple Ajax request being sent from my page /contact to a send action in /contact/send, passing in some POST data that then calls a send email function.

My javascript in the view is here:

$.ajax({
                type: "POST",
                url: '/contact/send',
                data: {
                    name: $('#input-name').val(),
                    email: $('#input-email').val(),
                    message: $('#input-message').val(),
                },
                dataType: "json",
                success: function (data) {
                    alert(data);
                    $('#contact-form').hide();
                    $('#ajax-loading').hide();
                    $('#ajax-success').fadeIn();
                },
                error: function (request, status, error) {                  
                    alert('There was a problem contacting the server.');
                    alert(request.responseText);
                }
});

And my ContactController.php has this:

public function sendAction() {
        ini_set('display_errors', 1);
        $request = new Request();
        if ($request->isAjax()) {
            $name = $this->request->getPost("name");
            $email = $this->request->getPost("email");
            $message = $this->request->getPost("message");
            $send = $this->sendMail($name, $email, $message);
            return $send;
        }
        return false;
}

Now when I invoke this Ajax request I get the 'There was a problem contacting the server.' alert with the error responseText being blank. HOWEVER, at the same time, I know the sendMail() function has completed successfully (and returned 'true') because I get the email in my inbox! So what is causing the sendAction() to return as an error?



85.5k
Accepted
answer

return $send; contents something crappy probably


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

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

            $data = $this->view->getParamsToView(); // so in our action we can say $this->view->setVar("success");
            $this->response->setContentType('application/json', 'UTF-8');

            $this->response->setJsonContent(["my data" => "yes"]);
        }
}

public function sendAction(){
    $this->view->success = true;

    return false; //-< very immportant
}

phalcon 3+